I am have two tables which I have left joined like so below to show me the pads by id added in descending order which works fine.
SELECT p.* FROM ruj_users_pad
AS p LEFT JOIN ruj_users
AS u ON p.user_id = u.id
WHERE u.status !=0
AND 1
AND p.status = 1
GROUP BY p.added_date
DESC LIMIT 0, 20
However, now I would like to retrieve a third table which also as an ‘added_date’ column combine it with the previous query to show the new descending order. The data from the third table is a generated from a button when users click to favorite the current item on the pad.
Here is what I have but it is not working.
SELECT p.*,f.added_date FROM ruj_users_pad
AS p LEFT JOIN ruj_users
AS u ON b.user_id=u.id
LEFT JOIN ruj_users_fave
AS f ON f.brag_id = u.id
WHERE u.status !=0
AND 1
AND p.status = 1
GROUP BY f.added_date DESC, b.added_date DESC
LIMIT 0, 20
The result returns the same as the first result. I don’t understand what could be wrong. I would like the result to take into consideration that there is an entry in the ruj_users_fave and combine it with the first result to bring the favorited pad to the top.
Help is greatly appreciated.
Here is a solution to your problem using
UNIONto merge two subqueries. It is not the full query of three tables but only the essence with two tables to demonstrate the concept. I use a tablepadand a tablelikes. The first subquery selects the pad’sidand its most recent “like” usingMAXtogether withGROUP BY id. Note that I rename the columnMAX(liked)totimestamp.The other subquery selects the pad
ids that were not liked yet, i.e. no record in the likes table exists for that specific padid. In this case, you mention that the pad’s creation date should be used for determining the order of records returned. Thus, we renameaddedtotimestamp.We have two subqueries now that return the pad’s
idand thetimestampso we can combine them to a single result set usingUNION, and thenORDERitBY timestamp. The combined query for you looks like this.