getaway
getaway

Reputation: 8990

Ordering mysql rows from derived columns

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

Upvotes: 2

Views: 1595

Answers (3)

seriyPS
seriyPS

Reputation: 7112

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!

Upvotes: 1

OMG Ponies
OMG Ponies

Reputation: 332661

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

Upvotes: 4

Bryan Denny
Bryan Denny

Reputation: 27596

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)

Upvotes: 7

Related Questions