Jump to content

MySQL sorting based on if row exists in another table.


meman1188

Recommended Posts

I am running the query to get data out of table A (items). If there is a corresponding row present in table B (redirects) then I want to sort off of A.`update` otherwise i want to sort off of A.`original`. Table B is accessed by key ex (A.`key` = B.`key`).

 

So this is sort of the sample i have right now but is not working:

SELECT `items`.* ,

CASE WHEN EXISTS (

SELECT 1 FROM `redirects` WHERE `redirects`.`key` = `items`.`key`

)

THEN `items`.`update`

ELSE `items`.`original`

END CASE AS `sort_by`

FROM `items`

WHERE (`items`.`key` = xxx)

ORDER BY `sort_by`DESC

 

Thanks for the help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.