0

我有一个名为引号的表:

id date       content
80 2012-06-03 This is the first quote.
81 2012-06-05 Lorem Ipsum.

还有一个名为评级的表格:

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 和评级信息?

非常感谢!

4

1 回答 1

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
于 2012-07-18T12:28:17.000 回答