在检查多个WHERE子句时,在SQL中连接两个表

时间:2017-04-29 10:26:13

标签: mysql sql-server

{{1}}

我有一个名为“players”的表,而“player_bans”表有一个“by_userid”列。这表明玩家被禁止的人。 player_bans表中的by_userid列与players表中的ID(唯一插入ID)相关。播放器表还有一个用户名字段,我想通过上面的查询获取。

因此,查询必须通过查看player_bans表中的by_userid字段,从players表中找到禁止用户的名称。

2 个答案:

答案 0 :(得分:1)

您需要使用JOIN,试试这个:

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

答案 1 :(得分:1)

您可以尝试以下查询:

SELECT t1.*, (`t1.expire_date` IS NULL) AS `permanent`,t2.username 
FROM `player_bans` as t1 INNER JOIN  `players` as t2 
ON t1.by_userid=t2.id
and (`ip` = '%e' OR `userid` = '%d') AND 
    (`expire_date` > NOW() OR `expire_date` IS NULL) 
LIMIT 1