我有3张桌子。游戏,FinalGame扩展游戏和参与者谁有游戏列表和FinalGame列表。现在我有问题。如何选择游戏,而不是最终游戏。如何选择只有游戏的参与者,而不是最终游戏。
在第一个选项中我试过:
select * from game g where {g.ID not in (select pl.game_id from PLAY_OFF_TABLE pl) }
但我不确定它是否正确。
我尝试了第二个选项;
select * from participant p left join game g1 on p.ID = g1.HOME_PARTICIPANT_ID
但是这会选择包括final在内的所有游戏。我不知道如何排除最终比赛
CREATE TABLE IF NOT EXISTS `GAME` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`HOME_PARTICIPANT_ID` int(11) DEFAULT NULL,
`AWAY_PARTICIPANT_ID` int(11) DEFAULT NULL,
`STATUS` enum('WIN','LOSE','DRAW') DEFAULT NULL,
`RESULT` varchar(50) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `HOME_PARTICIPANT_ID` (`HOME_PARTICIPANT_ID`),
KEY `AWAY_PARTICIPANT_ID` (`AWAY_PARTICIPANT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
CREATE TABLE IF NOT EXISTS `PLAY_OFF_GAME` (
`GAME_ID` int(11) NOT NULL,
`GROUP_ID` int(11) NOT NULL,
`POSITION` int(11) NOT NULL,
PRIMARY KEY (`GAME_ID`),
KEY `GROUP_ID` (`GROUP_ID`),
KEY `POSITION` (`POSITION`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `PARTICIPANT` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
更新:
select * from PARTICIPANT p left join GAME g1 on p.ID = g1.HOME_PARTICIPANT_ID join PLAY_OFF_GAME pl on g1.id = pl.GAME_ID where p.group_id = 441 and pl.GAME_ID is null
重新调整0行
select * from PARTICIPANT p left join GAME g1 on p.ID = g1.HOME_PARTICIPANT_ID left join PLAY_OFF_GAME pl on g1.id = pl.GAME_ID where p.group_id = 441 and pl.GAME_ID is null
返回5
select * from PARTICIPANT p left join GAME g1 on p.ID = g1.HOME_PARTICIPANT_ID left join PLAY_OFF_GAME pl on g1.id = pl.GAME_ID where p.group_id = 441
返回所有参与者8,但也是我要排除的最终游戏
答案 0 :(得分:1)
您的第一个查询会选择没有相应GAME
的{{1}}行,但加入可能会更快:
PLAY_OFF_GAME
对于第二个问题,你可以做同样的伎俩:
SELECT *
FROM GAME g
LEFT JOIN PLAY_OFF_GAME pog ON g.ID=pog.GAME_ID
WHERE pog.GAME_ID IS NULL;
查询可能有拼写错误。首先选择游戏中的Particpants,或者不选择任何游戏中的Particpants,但它仅在最终游戏中排除参与者。第二个选择填补了这些,忽略了游戏。
此外:
SELECT * FROM (
(SELECT p1.*, g.ID
FROM PARTIPANT p1
LEFT JOIN GAME g1 ON p1.ID=g1.HOME_PARTICIPANT_ID
LEFT JOIN PLAY_OFF_GAME pog1 ON g1.ID=pog1.GAME_ID
WHERE pog1.GAME_ID IS NULL)
UNION
(SELECT p2.*, NULL
FROM PARTICIPANT p2
JOIN GAME g2 ON p2.ID=g2.HOME_PARTICIPANT_ID
JOIN PLAY_OFF_GAME pog2 ON g2.ID=pog2.GAME_ID)) AS tmp;
添加到OR p.ID=g.AWAY_PARTICIPANT_ID
子句中。 (我跟着你的例子,但描述似乎不一致。ON
上是否应该有外键约束?例如,PLAY_OFF_GAME
?