2014-01-17 116 views
0

我正在嘗試使下面的查詢對另一個具有用戶名的表中的行進行計數。每個用戶名在統計表中有一行,但在用戶名爲pvp表中有多行。從pvptable加入的所有列顯示爲空,並且殺死了COUNT動態生成的死亡。這是SQL查詢。MySQL LEFT JOIN列爲空

SELECT 
    *, 
    pvptable.username AS USER, 
    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 = "Username" 
    AND pvptable.username = "Username" 
WHERE st.username = "Username" ; 
+4

您的加盟條件有點可疑。 –

+0

我會說, SELECT *,pvptable.username作爲用戶,COUNT(pvptable.killer)作爲殺害, COUNT(pvptable.username)作爲死亡, 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」; – TranQ

+0

將您的查詢更改爲此。編輯:「pvptable.killer = st.username」而不是「pvptable.killer =」用戶名「 – TranQ

回答

0

你混合wherejoin條件:

  • 時要涉及一個表中的字段與另一個表
  • 您使用where的字段您使用join當你想過濾您的表的數據

因此,要使您的查詢工作:

SELECT 
    *, pvptable.username as user, 
    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 -- Add some other relations if you need them 
WHERE 
    st.username="Username"; 
+0

這很好,但它顯示死亡數量相同作爲殺死:( – user3205106

+0

你需要調整這個以適合你的需求...在你的查詢中播放一下,直到你做出正確的選擇。重要的是:不要在'加入'條件下混合'where'條件。 – Barranka

+0

我試過'SELECT *,pvptable.username as user, COUNT(pvptable.killer)as kill, COUNT(pvptable.username)as deaths, ROUND(COUNT(pvptable.killer)/COUNT(pvptable.username),2)AS kd 從 stats as st LEFT JOIN pvp as pvptable ON pvptable.killer = st.Username AND pvptable.username = st.Username WHERE st.username =「tacoboboy32」;'但它不工作。它仍然表現出與死亡相同的死亡率。 – user3205106

0

做一個加入爲你想要的,然後使用COUNT(DISINCT ID)各統計(假設id是PVP表的唯一鍵),像這樣: -

SELECT st.username as user, 
    COUNT(DISTINCT pvptable_kills.id) as kills, 
    COUNT(DISTINCT pvptable_deaths.id) as deaths, 
    ROUND(COUNT(DISTINCT pvptable_kills.id)/COUNT(DISTINCT pvptable_deaths.id), 2) AS kd 
FROM stats as st 
LEFT OUTER JOIN pvp as pvptable_kills ON pvptable_kills.killer=st.Username 
LEFT OUTER JOIN pvp as pvptable_deaths ON pvptable_deaths.username=st.Username 
WHERE st.username="Username" 
GROUP BY st.username