【问题标题】:SQL SELECT name by idSQL SELECT name by id
【发布时间】:2014-12-29 21:24:11
【问题描述】:

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

我有这两张桌子:

player_locations:

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

users:

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

我需要选择从player_locations.playerid 中获取users.playername。我有获得player_locations.playerid 的独特位置。

伪查询:

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

输出应该是example1

【问题讨论】:

  • FROM users 应该是 FROM users, player_locations

标签: mysql sql select join


【解决方案1】:

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

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

在您的情况下,您可以使用来自用户的id 列和来自player_locationsplayerid 列来关联这两个表。您还可以在JOIN 语句中包含您的'DOWNTOWN' 要求。试试这个:

SELECT u.playername
FROM users u
JOIN player_locations pl ON pl.playerid = u.id AND pl.location = 'DOWNTOWN';

编辑

虽然我个人更喜欢上面的语法,但我希望您知道另一种与您现在类似的编写方式。

您还可以通过在FROM 子句中使用逗号分隔多个表来从多个表中进行选择。然后,在您的 WHERE 子句中,您可以插入您的条件:

SELECT u.playername
FROM users u, player_locations pl
WHERE u.id = pl.playerid AND pl.location = 'DOWNTOWN';

【讨论】:

  • SQL 从一开始就不容易。继续努力,你很快就会解决这些问题。很高兴我能帮上忙。
【解决方案2】:

这是解决方案。

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

【讨论】:

    【解决方案3】:

    我有个主意,试试这个:

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

    【讨论】:

      猜你喜欢
      • 2013-03-25
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      相关资源
      最近更新 更多