MySQL self-referencing ID and selects

2019-09-08 23:04发布

I have a MySQL table here Starcraft2brackets:

http://i.stack.imgur.com/welPq.png (re-edited so I could edit again, sorry first editor)

uId => reference to a user

id => the index

opponent => reference to id in this table, -2 is considered a bye.

What I am trying to do, is come up with a sql statement that will select a username based upon the uId of a row, as well as select the username of their opponent. The most constructive one I have come up with so far was

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

This did give me the correct usernames, however it gave duplicate entries, like so..

http://i.imgur.com/znbAi.png

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

This gave me the result set I was looking for exactly. Thanks for the help stackoverflow.com.

标签: mysql
1条回答
小情绪 Triste *
2楼-- · 2019-09-08 23:53

Try this:

SELECT u1.username, if(u1.oppponent = -2, "Bye", u2.username) as username
FROM users AS u1
left join users AS u2 on u1.opponent = u2.id
join Starcraft2brackets AS sc2a on u1.id = sc2a.uId
where u1.uid = ?;
查看更多
登录 后发表回答