MySQL通过另一个表中的投票进行排序

时间:2014-02-03 01:28:25

标签: mysql join

我有这样的表:

entries:

ID      TITLE
1       Xyhargka
2       Hypothermia
3       Scale

votes:

ID      VOTE1       VOTE2   USERNAME
1       1           2       Entity
2       1           3       RobertG

VOTE1和VOTE2具有条目ID。 VOTE1计数为2票,VOTE2计为1票。

我正在尝试构建一个返回此内容的查询:

ID      TITLE           VOTES
1       Xyhargka        3
3       Scale           2
2       Hypothermia     1

我一直在看JOIN语句,但我似乎无法弄清楚......我知道这不是有效的MySQL,但这里是我想要的伪代码:

SELECT v1 + v2 as votes, entries.* FROM entries
    JOIN (SELECT count(vote1) * 2 as v1 FROM votes WHERE vote1 = entries.id)
    JOIN (SELECT count(vote2) * 1 as v2 FROM votes WHERE vote2 = entries.id)
ORDER BY votes

1 个答案:

答案 0 :(得分:1)

这就是我在SQLSERVER中的做法,不确定MySQL中是否存在差异

SELECT V.ID,
  SUM( V.COUNT) AS TOTALCOUNT
FROM  (SELECT E1.ID AS ID, 2 AS COUNT
FROM VOTES AS V
JOIN ENTRIES AS E1
  ON V.VOTE1 = E1.ID
UNION ALL
SELECT E2.ID AS ID, 1 AS COUNT
FROM VOTES AS V
JOIN ENTRIES AS E2
  ON V.VOTE2 = E2.ID) AS V
GROUP BY V.ID
ORDER BY TOTALCOUNT DESC