我正在从我的数据库中选择各种列,我的查询如下所示:
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 的值。
我将如何修改我的查询以接收实际分数?
最佳答案
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
因为每个故事都可以有很多句子和很多选票,所以您通过乘以所有可能的连接得到笛卡尔积。
关于php - MySQL将字段结果乘以另一个字段的编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12866473/