简体   繁体   English

MySQL LEFT JOIN查询显示相同的值

[英]MySQL LEFT JOIN query shows same value

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. stats表中的每个用户名都有1行,而pvp表中的每个用户名都包含多行。 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 这是一个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";
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 DEMO

To do it for everyone, use GROUP BY : 为此,请使用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 DEMO

COUNT(foo) and COUNT(bar) both count the number of rows in the resultset, you might as well say COUNT(*) in both cases. COUNT(foo)COUNT(bar)都计算结果集中的行数,在这两种情况下您都可以说COUNT(*)

You need to COUNT(*) FROM ... GROUP BY killer to get the number of killers, for example. 例如,您需要COUNT(*) FROM ... GROUP BY killer以获得COUNT(*) FROM ... GROUP BY killer的数量。 Not sure what the table structure is to give you a full answer. 不确定表的结构将为您提供完整的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM