我在MySql中有两个查询
SELECT DISTINCT Game.mID
FROM Game, SlotGame
WHERE Game.gID=SlotGame.gID
SELECT DISTINCT Game.mID
FROM Game, TableGame
WHERE Game.gID=TableGame.gID
我需要将这两个查询的结果相交。
表格如下:
游戏(gID是主键): SlotGame:
TableGame:
我的预期答案应该是mID:01 注意:SlotGame和TableGame将具有唯一的gID值
答案 0 :(得分:2)
您可以通过Game
表连接两次,使用两个不同的别名,其中连接条件是mID
的相等。前提是每个游戏类型表(Slot,Table)仍然加入Game
并返回mID
。合并后,它们将成为mID
的超集,但如果您对这些内容执行INNER JOIN
,则任何不常见的内容都将从该集合中丢弃。您是SELECT gt.mID
还是SELECT gs.mID
是否无关紧要,因为其余的值在联接的两边都是相同的。
SELECT DISTINCT
gt.mID
FROM
Game gs
/* join Game to itself */
INNER JOIN Game gt ON gs.mID = gt.mID
/* and join each of the other tables to one of the Game joins */
INNER JOIN SlotGame ON gs.gID = SlotGame.gID
INNER JOIN TableGame ON gt.gID = TableGame.gID
以下是您的行示例:http://sqlfiddle.com/#!2/f57c3d/8
并证明它可以扩展几行:http://sqlfiddle.com/#!2/afe66e
答案 1 :(得分:1)
SELECT G1.mID
FROM
(
SELECT DISTINCT Game.mID
FROM Game, SlotGame
WHERE Game.gID=SlotGame.gID
) G1
JOIN
(
SELECT DISTINCT Game.mID
FROM Game, TableGame
WHERE Game.gID=TableGame.gID
) G2
ON G1.mID = G2.mID