我从我的数据库中选择了各种列,我的查询如下所示:
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。
<小时/> 如何修改我的查询以获得实际分数?
答案 0 :(得分: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
因为每个故事可以有很多句子和很多票,所以你可以通过乘以所有可能的连接来获得笛卡尔积。