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?
As a very broad description, you can think of SQL query execution as consisting of separate stages:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.