我有一个三表设置:孩子、玩具和游戏,每个都有唯一的主键:id_kid、id_toy 和 id_game。每个孩子可以拥有多个玩具和游戏,但每个玩具或游戏只有一个孩子拥有。
玩具和游戏有一个带有 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 个游戏。(都错了)
请帮助回答 - 如果可能的话 - 不使用子选择。谢谢你。