[英]how to conditionally order by two different categories from two different tables
我有3張桌子連在一起。 其中兩個表(“ posts”和“ shared_posts”)具有日期類別。 我想按日期排序,但是如果shared_posts.username = $username
我希望它使用shared_posts.date而不是posts.date。 (反之亦然)
我不確定該怎么做。 到目前為止,這就是我所擁有的...
SELECT postid, posts.date, shared_posts.date, posts.username, posts.title
FROM posts
LEFT JOIN posts_views_likes USING (postid)
LEFT JOIN shared_posts USING (postid)
WHERE posts.username = '" . $username . "'
OR shared_posts.username = '" . $username . "'
ORDER BY posts.date DESC, shared_posts.date DESC
什么是最有效的方法?
您可以在ORDER BY
子句中使用CASE
:
ORDER BY
CASE WHEN shared_posts.username = '" . $username ."'
THEN shared_posts.date
ELSE posts.date
END DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.