我正在尝试这样做,以便下面的查询计算来自另一个具有用户名的表的行,然后是具有杀手的死亡。统计信息表中每个用户名有1行,但pvp表中有多行用户名。出于某种原因,死亡列与杀戮列的数量相同,有谁知道为什么?这是我的查询。这是一个sql小提琴我想我得到了正确的idk如何使用sqlfiddle:http://sqlfiddle.com/#!2/b793b/1
SELECT
*,
COUNT(pvptable.killer) as kills,
COUNT(pvptable.username) as deaths,
ROUND(COUNT(pvptable.killer) / COUNT(pvptable.username), 2) as kd
FROM
stats as st
LEFT JOIN pvp as pvptable ON pvptable.killer=st.username
WHERE
st.username="Username";
答案 0 :(得分:1)
SELECT st.*,
SUM(pvp.killer = st.username) AS kills,
SUM(pvp.username = st.username) as deaths
FROM stats AS st
LEFT JOIN pvp ON pvp.username = st.username OR pvp.killer = st.username
WHERE st.username = "Username"
要为所有人执行此操作,请使用GROUP BY
:
SELECT st.*,
SUM(pvp.killer = st.username) AS kills,
SUM(pvp.username = st.username) as deaths
FROM stats AS st
LEFT JOIN pvp ON pvp.username = st.username OR pvp.killer = st.username
GROUP BY st.username
答案 1 :(得分:0)
COUNT(foo)
和COUNT(bar)
都会计算结果集中的行数,在这两种情况下您都可以说COUNT(*)
。
例如,您需要COUNT(*) FROM ... GROUP BY killer
来获取杀手的数量。不确定表结构是什么给你一个完整的答案。