开发者

Ordering mysql rows from derived columns

开发者 https://www.devze.com 2023-01-23 05:25 出处:网络
I wanted to retrieve rows from the mysql database and order them by votes: votes_up + votes_down = votes

I wanted to retrieve rows from the mysql database and order them by votes:

votes_up + votes_down = votes

table:

posts{id, post_text, votes_up, votes_down, date}
ORDER 开发者_如何学编程BY votes


SELECT id, post_text, votes_up, votes_down, date, sum(votes_up + votes_down) as 'Votes'
FROM posts
ORDER BY sum(votes_up + votes_down)


Traditional SQL allows you to use column aliases in the ORDER BY:

  SELECT p.votes_up + p.votes_down AS total_votes
    FROM POSTS p
ORDER BY total_votes


You can use blablabla ORDER BY sum(votes_up + votes_down), but be careful and don't use this on high-loaded production databases, because sum() will be calculeted "on the fly" and it will be very slow for large tables!

0

精彩评论

暂无评论...
验证码 换一张
取 消