I have a generic function (php) that retrieves multiple records of a table by matching a column value and orders them by a datetime field. In some instances the datetime is the same for multiple records, inserted at nearly the same time, and on these tables there is another column that is a record number, an automatically incrementing number. I would like to check if the table has this record number column present, and if so, sort by it. Otherwise if the record number column does not exist in the table I want to sort by the datetime field. I could write a separate function, sorting for record numbers, but prefer this to be handled by a single function using a mysql solution.
I just want to know if this can be done?
Using IF, Exist, or orderby?
CodePudding user response:
As a very broad description, you can think of SQL query execution as consisting of separate stages:
- Parsing the query: checking the syntax, working out which bits are table names, where strings begin and end, whether it's a SELECT or an UPDATE, etc. This is where MySQL takes the string provided by PHP and breaks it into some internal pieces.
- Planning the query: working out what tables and columns are involved, how they need to be filtered and manipulated, what indexes and optimisations can be used. The only unknowns left are the placeholders you use for your data to prevent SQL Injection.
- Executing the query: plugging in actual values, fetching indexes and data, and running through the steps of the plan to give the desired output or effect. This is where the actual values you bound to your placeholders are used.
The important point is that step 2 generally doesn't deal with "if" and "maybe", it expects to be told directly "use this column, of this table". Any choice of what table to use would have to happen before anything hits the database.
In your case, that means the choice of table happens in PHP; but PHP is just building a string, it doesn't know about what columns exist, so it can't automatically make this decision either.
In short, you will need to write some custom code to do this: have a list of which tables use which column to sort; or make an extra query to a system view like INFORMATION_SCHEMA.COLUMNS
to look it up, and then have the conditional logic in PHP.