我有一個三表設置:孩子們,玩具和遊戲,每個都有獨特的主鍵:id_kid,id_toy和id_game。每個孩子可以有多個玩具和遊戲,但每個玩具或遊戲只有一個孩子。MySQL使用總和和左連接加倍結果
的玩具和遊戲有3個狀態買走列:1,0,1 表結構是這樣的:
kids
id_kid
kid_name
etc
games
id_game
id_kid_games --> links with id_kid in kids_table (maybe not the best name, I know)
game_name
bought --> can be -1,0,1
toys
id_toy
id_kid_toys --> links with id_kid in kids_table
toy_name
bought --> can be -1,0,1
對於每個孩子我試圖得到一個總的玩具和遊戲,買和不買的,使用下面的查詢,但結果一倍:
SELECT kids.*,
COUNT(DISTINCT toys.id_toy) AS total_toys,
SUM(CASE toys.bought WHEN 1 THEN 1 ELSE 0 END) AS toys_bought,
SUM(CASE toys.bought WHEN -1 THEN 1 ELSE 0 END) AS toys_not_bought,
COUNT(DISTINCT games.id_game) AS total_games,
SUM(CASE games.bought WHEN 1 THEN 1 ELSE 0 END) AS games_bought,
SUM(CASE games.bought WHEN -1 THEN 1 ELSE 0 END) AS games_not_bought
FROM kids as k
LEFT JOIN toys t ON k.id_kid = t.id_kid_toys
LEFT JOIN games g ON k.id_kid = g.id_kid_games
GROUP BY k.id_kid
ORDER BY k.name ASC
一個孩子已經2個玩具和4場,都買了,結果是2層總的玩具(正確)總共4款遊戲(正確),購買8款玩具,購買8款遊戲。 (都是錯誤的)
請幫忙做出答案 - 如果可能的話 - 不使用子查詢。 謝謝。
你可以發佈每個表的樣本數據以及表結構嗎? – Taryn
@bluefeet我編輯了這個問題,並試圖解釋表結構。謝謝。 – noru
謝謝你,你可以發佈一些樣本數據? – Taryn