1

我正在从我的数据库中选择各种列,我的查询如下所示:

SELECT st.* , u.username creator, COUNT(DISTINCT se.sentenceid) AS sentences,
  COALESCE(SUM(v.vote), 0) score, 
  GROUP_CONCAT(se.text ORDER BY se.sentenceid SEPARATOR  ' ') text
FROM stories st
JOIN sentences se ON st.storyid = se.storyid
LEFT OUTER JOIN votes v ON st.storyid = v.storyid
LEFT OUTER JOIN users u ON st.creatorid = u.userid
GROUP BY st.storyid
LIMIT 30

此查询适用于除分数之外的所有内容。输出分数是句子数乘以实际分数。我的votes表如下所示:

+---------+------------+------+-----+---------+-------+
| Field   | Type       | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| userid  | int(11)    | YES  | MUL | NULL    |       |
| storyid | int(11)    | NO   | MUL | NULL    |       |
| vote    | tinyint(4) | NO   |     | NULL    |       |
+---------+------------+------+-----+---------+-------+

vote包含值 1 或 -1。


我将如何修改我的查询以接收实际分数?

4

1 回答 1

3
SELECT st.* , u.username creator, COUNT(DISTINCT se.sentenceid) AS sentences,
  COALESCE((SELECT SUM(v.vote)
            FROM votes v
            WHERE st.storyid = v.storyid), 0) score, 
  GROUP_CONCAT(se.text ORDER BY se.sentenceid SEPARATOR  ' ') text
FROM stories st
JOIN sentences se ON st.storyid = se.storyid
LEFT OUTER JOIN users u ON st.creatorid = u.userid
GROUP BY st.storyid
LIMIT 30

因为每个故事都可以有很多句子和很多选票,所以通过将所有可能的连接相乘,您将得到一个笛卡尔积。

于 2012-10-12T20:28:53.677 回答