在第二个表中按匹配选择顺序

时间:2012-04-13 16:07:00

标签: mysql sql

我在尝试按照投票次数选择的项目时遇到一些麻烦。 投票是在一个单独的表中进行,但订单没有以正确的顺序出现。

有人能指出这出错的地方吗?

CompetitionEntries(未在查询中使用但可能相关)

id | PhotoTitle
=======================
23 |   'Photo 1'
24 |   'Photo 2'
25 |   'Photo 3'
26 |   'Photo 4'
=======================

CompetitionVotes

id | IdOfPhotoVotedOn
=======================
10 |   23
11 |   24
12 |   22
13 |   22
14 |   22
15 |   24
=======================

我正在尝试使用下面显示的语句“

SELECT `IdOfPhotoVotedOn`, COUNT(`IdOfPhotoVotedOn`) 'Votes' 
FROM `CompetitionVotes` 
WHERE 1
GROUP BY `IdOfPhotoVotedOn`
ORDER BY 'Votes' DESC, `IdOfPhotoVotedOn`

我得到的是

IdOfPhotoVotedOn | Votes
==========================
   22            |   3
   23            |   1
   24            |   2

我想要的是

IdOfPhotoVotedOn | Votes
==========================
   22            |   3
   24            |   2
   23            |   1

2 个答案:

答案 0 :(得分:2)

SELECT * FROM 
(SELECT `IdOfPhotoVotedOn`, COUNT(`IdOfPhotoVotedOn`) 'Votes' 
FROM `CompetitionVotes` 
WHERE 1
GROUP BY `IdOfPhotoVotedOn`) A
ORDER BY A.Votes DESC;  

答案 1 :(得分:2)

试试这个?

SELECT `IdOfPhotoVotedOn`, COUNT(`IdOfPhotoVotedOn`) 'Votes' 
FROM `CompetitionVotes` 
WHERE 1
GROUP BY `IdOfPhotoVotedOn`
ORDER BY COUNT(`IdOfPhotoVotedOn`) DESC, `IdOfPhotoVotedOn`