所以我需要加入5个表。其中一个我有问题。它有2列,它们是不同表的相同外键,即
matchdetail
idmatch | idplayer1 | idplayer2 | time | (FK) idmatchnight (FK)
这是
之间的联结表player
(PK) idplayer | firstname | secondname | nationality
matchnight
(PK) idmatchnight | location
我的sql查询应该是什么?
我目前的代码:doent work
SELECT * FROM player
INNER JOIN coach ON player.idcoach = coach.idcoach
INNER JOIN sponsor ON player.idsponsor = sponsor.idsponsor
INNER JOIN matchdetail ON player.idplayer = matchdetail.idplayer1
AND player.idplayer = matchdetail.idplayer2
INNER JOIN matchnight ON matchdetail.idmatch
WHERE player.idplayer=:idplayer
;"
idmatch是代理主键而不是复合键
答案 0 :(得分:1)
重新编写查询可能会更好:
SELECT ...
FROM matchdetail
INNER JOIN player AS p1 ON matchdetail.player1=p1.idplayer
INNER JOIN player AS p2 on matchdetail.player2=p2.idplayer
etc...
您当前的加入基本上只允许玩家玩THEMSELVES的比赛。通过两次加入player
,您可以获得两个不同玩家的详细信息。
答案 1 :(得分:1)
如果您想保留此逻辑,您还可以使用OR代替AND:
SELECT * FROM player
INNER JOIN coach ON player.idcoach = coach.idcoach
INNER JOIN sponsor ON player.idsponsor = sponsor.idsponsor
INNER JOIN matchdetail ON (player.idplayer = matchdetail.idplayer1
OR player.idplayer = matchdetail.idplayer2)
INNER JOIN matchnight ON matchdetail.idmatch
WHERE player.idplayer=:idplayer;
问题在于,使用当前谓词(使用AND),它基本上与以下内容相同:
player.idplayer = matchdetail.idplayer1 = matchdetail.idplayer2
答案 2 :(得分:0)
SELECT columns, you, actually, want
FROM matchnight m
JOIN matchdetail d
ON d.idmatchnight = m.idmatchnight
JOIN player p1
ON p1.idplayer = d.idplayer1
JOIN player p2
ON p2.idplayer = c.idplayer2;
答案 3 :(得分:0)
感谢大家的回答
我自己找到了一个解决方案:)SELECT * FROM matchdetail
INNER JOIN boxer ON matchdetail.idplayer1
AND matchdetail.idplayer2
INNER JOIN coach ON player.idcoach = coach.idcoach
INNER JOIN sponsor ON player.idsponsor = sponsor.idsponsor
INNER JOIN matchnight ON matchdetail.idmatchnight = matchnight.idmatchnight
WHERE player.idplayer