我可以请求您提供多对多的查询帮助吗?
我有一个使用MS Access 2010构建的ACE数据库。它有以下表格。
Flags
flagID flagName country
1 Stars and Stripes USA
2 French Tricolour France
3 The Yellow and Blue Sweden
4 Union Jack UK
5 Jolly Roger Pirates
6 Trinacria Sicily
Colours
colourID colour
1 Red
2 Blue
3 White
4 Black
5 Yellow
Juntion
JID fkFlags fkColours
For brevity, I’ll omit the field values from the Junction table.
如果我用
查询表格SELECT Flags.flagName, Flags.country, Colours.colour
FROM Flags INNER JOIN
(Colours INNER JOIN Juntion ON Colours.colourID = Juntion.fkColours)
ON Flags.flagID = Juntion.fkFlags
WHERE Flags.flagName = 'Jolly Roger' OR Flags.flagName = 'Stars and Stripes';
我的结果是我所期待的。
flagName country colour
Stars and Stripes USA Red
Stars and Stripes USA White
Stars and Stripes USA Blue
Jolly Roger Pirate Black
Jolly Roger Pirate White
同样,如果我用
查询表格SELECT Flags.flagName, Flags.country, Colours.colour
FROM Flags INNER JOIN (Colours INNER JOIN Juntion ON Colours.colourID = Juntion.fkColours)
ON Flags.flagID = Juntion.fkFlags
WHERE Colours.Colour IN ((
SELECT C.colour
FROM Flags INNER JOIN (Colours C INNER JOIN Juntion ON C.colourID = Juntion.fkColours)
ON Flags.flagID = Juntion.fkFlags
WHERE (c.Colour = 'White')
))
OR Colours.Colour IN ((
SELECT C.colour
FROM Flags INNER JOIN (Colours C INNER JOIN Juntion ON C.colourID = Juntion.fkColours)
ON Flags.flagID = Juntion.fkFlags
WHERE (c.Colour = 'Blue')
))
我的结果是我所期待的。
flagName country colour
Stars and Stripes USA White
Stars and Stripes USA Blue
The Yellow and Blue Sweden Blue
Jolly Roger Pirate White
French Tricolor France Blue
French Tricolor France White
Union Jack UK White
Union Jack UK Blue
然而,我真正想要的是获得所有flagNames的结果,其中color = Red,White和Blue。
Stars and Stripes
French Tricolour
Union Jack
另外,鉴于'星条旗'和'Jolly Roger'的旗帜,他们分享了什么颜色?
White
在上面的最后一个查询示例中,如果我将OR更改为AND,则根本不会返回任何结果。我可以请你帮忙写这些问题吗?
感谢您的时间。
答案 0 :(得分:2)
对于具有所有三种颜色的标志:
SELECT flagName
FROM Flags
WHERE
flagID IN
(
SELECT Juntion.fkFlags
FROM Juntion INNER JOIN Colours ON Juntion.fkColours = Colours.colourID
WHERE Colours.colour = "Red"
)
AND flagID IN
(
SELECT Juntion.fkFlags
FROM Juntion INNER JOIN Colours ON Juntion.fkColours = Colours.colourID
WHERE Colours.colour = "White"
)
AND flagID IN
(
SELECT Juntion.fkFlags
FROM Juntion INNER JOIN Colours ON Juntion.fkColours = Colours.colourID
WHERE Colours.colour = "Blue"
)
同样,对于两个标志之间的常见颜色
SELECT colour
FROM Colours
WHERE
colourID IN
(
SELECT Juntion.fkColours
FROM Juntion INNER JOIN Flags ON Juntion.fkFlags = Flags.flagID
WHERE Flags.flagName = "Stars and Stripes"
)
AND colourID IN
(
SELECT Juntion.fkColours
FROM Juntion INNER JOIN Flags ON Juntion.fkFlags = Flags.flagID
WHERE Flags.flagName = "Jolly Roger"
)