mag*_*1te 0 mysql sql select join
我需要有关sql查询的帮助.
我有这两个表:
player_locations:
ID | playerid | location <- unqiue key
---|-----------------------
1 | 1 | DOWNTOWN
Run Code Online (Sandbox Code Playgroud)
和 users:
ID | playername | [..]
----|--------------------
1 | example1 | ...
Run Code Online (Sandbox Code Playgroud)
我需要一个选择,以获得users.playername从player_locations.playerid.我有独特的地理位置player_locations.playerid.
伪查询:
SELECT playername
FROM users
WHERE id = player_locations.playerid
AND player_locations.location = "DOWNTOWN";
Run Code Online (Sandbox Code Playgroud)
输出应该是example1.
这只是一个简单的问题INNER JOIN.JOIN的一般语法是:
SELECT stuff
FROM table1
JOIN table2 ON table1.relatedColumn = table2.relatedColumn
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以使用id来自用户和playerid列的列来关联这两个表player_locations.您还可以'DOWNTOWN'在JOIN声明中包含您的要求.试试这个:
SELECT u.playername
FROM users u
JOIN player_locations pl ON pl.playerid = u.id AND pl.location = 'DOWNTOWN';
Run Code Online (Sandbox Code Playgroud)
编辑
虽然我个人更喜欢上面的语法,但我希望您能够了解另一种编写方法,这与您现在的方法类似.
您还可以使用FROM子句中的逗号从多个表中进行选择以将它们分开.然后,在您的WHERE条款中,您可以插入您的条件:
SELECT u.playername
FROM users u, player_locations pl
WHERE u.id = pl.playerid AND pl.location = 'DOWNTOWN';
Run Code Online (Sandbox Code Playgroud)