0
我有一個MySQL表這裏Starcraft2brackets:MySQL的自參照的ID和選擇
http://i.stack.imgur.com/welPq.png(重新編輯,所以我可以重新編輯,遺憾第一編輯器)
UID =>參照用戶
id =>索引
opponent =>在此表中引用id,-2被認爲是再見。
我想要做的是提出一個sql語句,它將根據行的uId選擇一個用戶名,以及選擇他們的對手的用戶名。最有建設性的一個我想出迄今是
SELECT u1.username, if(sc2a.opponent = -2, "Bye", u2.username) as username
FROM Starcraft2brackets AS sc2a
LEFT JOIN users AS u1 ON u1.id = sc2a.uId
LEFT JOIN Starcraft2brackets AS sc2b ON sc2a.opponent = sc2b.id
LEFT JOIN users AS u2 ON sc2b.uId = u2.id
這確實給我正確的用戶名,但它給了重複的條目,像這樣..
SELECT u1.username, IF(sc2a.opponent = -2, "Bye", u2.username) AS username
FROM Starcraft2brackets AS sc2a
LEFT JOIN users AS u1 ON u1.id = sc2a.uId
LEFT JOIN Starcraft2brackets AS sc2b ON sc2a.opponent = sc2b.id
LEFT JOIN users AS u2 ON sc2b.uId = u2.id
WHERE u1.username < u2.username
OR sc2a.opponent = -2
這給了我準確的結果集。感謝您的幫助stackoverflow.com。