SQL SELECT名称由id

时间:2014-12-29 21:24:12

标签: mysql sql select join

我需要有关sql查询的帮助。

我有这两张桌子:

player_locations:

ID |  playerid  | location <- unqiue key
---|-----------------------
 1 |    1       | DOWNTOWN

users:

ID  | playername | [..]
----|--------------------
 1  | example1   | ...

我需要一个选择来从users.playername获取player_locations.playerid。我有唯一的位置来获取player_locations.playerid

伪查询:

SELECT playername 
FROM users
WHERE id = player_locations.playerid 
  AND player_locations.location = "DOWNTOWN";

输出应为example1

3 个答案:

答案 0 :(得分:6)

这只是一个简单的INNER JOINJOIN的一般语法是:

SELECT stuff
FROM table1
JOIN table2 ON table1.relatedColumn = table2.relatedColumn

在您的情况下,您可以使用用户的id列和playerid的{​​{1}}列来关联这两个表。您还可以在player_locations声明中添加'DOWNTOWN'要求。试试这个:

JOIN

修改

虽然我个人更喜欢上述语法,但我希望您能够了解另一种写入此内容的方法,这与您现在的方法类似。

您还可以使用SELECT u.playername FROM users u JOIN player_locations pl ON pl.playerid = u.id AND pl.location = 'DOWNTOWN'; 子句中的逗号从多个表中进行选择以将它们分开。然后,在您的FROM条款中,您可以插入条件:

WHERE

答案 1 :(得分:3)

这是解决方案。

SELECT
playername
FROM users
WHERE id = (SELECT id FROM player_locations WHERE location='DOWNTOWN')

答案 2 :(得分:2)

我有个主意,试试这个:

SELECT playername 
FROM users
WHERE id IN (SELECT DISTINCT playerid FROM player_location WHERE location LIKE "DOWNTOWN");