使用MySQL连接并从不同的插入ID中获取行

时间:2017-05-04 14:45:12

标签: mysql

SELECT pb.*
     , expire_date IS NULL permanent
     , p.username banned_by 
  FROM player_bans pb 
  JOIN players p 
    ON pb.by_userid = p.id 
 WHERE (ip = '%e' OR userid = '%d') 
   AND (expire_date > NOW() OR expire_date IS NULL) 
   AND liftedby_userid IS NULL 
 LIMIT 1

如您所见,查询加入“players”表并获取“username”行。我还希望通过加入表来获取播放器表上的用户标识(此userid字段存在于player_bans表中),如何在同一查询中执行此操作?

基本上,我想用by_userid做同样的事情,但是对于同一查询中的“userid”字段。

1 个答案:

答案 0 :(得分:0)

SELECT pb.*
     , (expire_date IS NULL) AS permanent
     , p1.username AS banned_by
     , p2.username AS player
FROM player_bans pb
JOIN players p1 ON pb.by_userid = p1.id
JOIN players p2 ON pb.userid = p2.id
WHERE (ip = '127.0.0.1' OR userid = 1)
  AND (expire_date > NOW() OR expire_date IS NULL)
  AND (liftedby_userid IS NULL)

这就是我解决它的方法。