我有一个名为quotes的表:
id date content
80 2012-06-03 This is the first quote.
81 2012-06-05 Lorem Ipsum.
一张名为rating的表:
rid uid qid rating
1 4 80 -1
2 4 81 1
uid字段是指进行该评级的登录用户。报价网站仅供登录用户使用,我希望能够向当前用户显示报价,包括指示报价当前评级的信息,是否对报价进行评级,如果是,他们评价了什么它作为。评级可以是-1或1.引号与提交它们的用户无关。
如果我只想获取一个引号,我执行此查询(例如引用80和用户4):
SELECT
q.id AS qid, q.content, q.date,
COALESCE(SUM(r.rating), 0) AS rating,
(SELECT COALESCE(rating, 0) FROM ratings WHERE qid = 80 AND uid = 4 LIMIT 1)
AS user_rated
FROM quotes q
LEFT JOIN ratings r ON q.id = r.qid
WHERE q.id = 80
GROUP BY q.id
我如何修改它以显示多个报价(即不只是报价ID 80),但保留user_rated和评级信息?
非常感谢!
答案 0 :(得分:1)
SELECT
q.id AS qid,
q.content,
q.date,
COALESCE(SUM(r.rating), 0) AS rating,
COALESCE(SUM(IF(r.uid = 4, r.rating, NULL)), 0) AS user_rated
FROM quotes q
LEFT JOIN ratings r ON q.id = r.qid
GROUP BY q.id