我的问题是我有2张桌子:
构建(此处存储了98%的信息)
地图(为地图创建每个构建,这些都在此处列出)
投票(每个用户为特定版本投票存储在此处)
现在我想根据他们收到多少票来对Builds进行排序,但是如果我做一个简单的LEFT Join,我会从给定的每个Vote中获得多个来自相同构建的行。 相反,我希望最后添加所有的投票,而不是:
因此我宁愿:
以下是我用于搜索/排序的代码
$query = sprintf('
SELECT
b.*, maps.name AS mapname, votes.vote AS vote
FROM
builds as b
INNER JOIN
maps ON maps.id = b.map
LEFT JOIN
votes ON votes.fk_build = b.id
WHERE
fk_buildstatus = 1 AND
' . implode(' ', $set) . ' 1=1
ORDER BY ' . $by . ' ' . $order . '
' . $limitcode);
基本上你可以忽略WHERE及以下的所有内容,只是为了完成而发布它
(我希望你能理解我,而且我的问题不是“noobish”)
编辑:感谢评论中提到的Sum函数,通过修改我的查询解决了我的问题:
$query = sprintf('
SELECT
b.*, maps.name AS mapname, IFNULL(SUM(votes.vote), 0) AS votes
FROM
builds as b
INNER JOIN
maps ON maps.id = b.map
LEFT JOIN
votes ON votes.fk_build = b.id
WHERE
fk_buildstatus = 1 AND
' . implode(' ', $set) . ' 1=1
GROUP BY
b.id
ORDER BY ' . $by . ' ' . $order . '
' . $limitcode);
答案 0 :(得分:1)
SELECT
b.*, maps.name AS mapname, SUM(IFNULL(votes.vote,0)) AS vote
FROM
builds as b
INNER JOIN
maps ON maps.id = b.map
LEFT JOIN
votes ON votes.fk_build = b.id
group by /* Add your group by columns here */