MySQL Two databases, order by one column in one case, order by another column in different case MySQL Two databases, order by one column in one case, order by another column in different case php php

MySQL Two databases, order by one column in one case, order by another column in different case


The field you are ordering by doesn't have to be an existing field in the database. You can also use a field you define in your select:

SELECT IF(records.userid = ' . $userid . ', records.whenadded, likes.whenliked) as date 

Now you can use it in the order by part:

ORDER BY date DESC

From the MySQL Manual:

A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses


I would suggest to separate the query into 2 query and use UNION instead.

SELECT * FROM((SELECT records.rid, records.userid,records.title, records.whenadded as adate        FROM records,likes         WHERE records.userid =  $userid   AND records.public = 1 )UNION(SELECT records.rid, records.userid,records.title, likes.whenliked as adate         FROM records,likes         WHERE records.rid = likes.rid AND likes.userid = $userid            AND records.public = 1) )t ORDER BY adate DESC

EDITED:Please refer to http://sqlfiddle.com/#!2/9a877/4


How about this:

$userid = 212;$SQL = 'SELECT DISTINCT records.*         FROM records,likes         WHERE (records.userid = ' . $userid .           ' AND records.public = 1)             OR (records.id = likes.rid AND likes.userid = ' . $userid .           ' AND records.public = 1)         ORDER BY records.userid, likes.whenliked DESC, records.whenadded DESC         LIMIT 50;';

This will separate the records-by-user and likes-by-user first and then by the date.