MySQL LEFT JOIN query shows same value

二次信任 提交于 2019-12-25 11:48:35

问题


I am trying to make it so that this query below counts rows from another table that have the username, then deaths that have killer. There is 1 row per username in the stats table, but multiple rows with in the pvp table with the username. The deaths column is the same amount as the kills column for some reason, does anyone know why? Here is my query. Here is a sql fiddle I think I got it right idk how to use 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";

回答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"

DEMO

To do it for everyone, use 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

DEMO




回答2:


COUNT(foo) and COUNT(bar) both count the number of rows in the resultset, you might as well say COUNT(*) in both cases.

You need to COUNT(*) FROM ... GROUP BY killer to get the number of killers, for example. Not sure what the table structure is to give you a full answer.



来源:https://stackoverflow.com/questions/21198444/mysql-left-join-query-shows-same-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!