将第二个MySQL表中的数据添加到第一个MySQL表中的结果

时间:2019-10-29 15:59:21

标签: mysql sql select

我有2张桌子:

+-----------+
|   users   |
+-----------+
|   John    |
|   Peter   |
|   Alex    |
+-----------+

+-----------+
|   banned  |
+-----------+
|   John    |
|   Peter   |
+-----------+

是否可以SELECT * FROM users并将结果与​​第二张表合并,以找出用户是否被禁止?

1 个答案:

答案 0 :(得分:2)

您可以使用LEFT JOIN使用以下内容:

-- with CASE WHEN
SELECT users.*, CASE WHEN banned.username IS NULL THEN 0 ELSE 1 END AS isBanned
FROM users LEFT JOIN banned ON users.username = banned.username

-- without CASE WHEN (thanks to @forpas!)
SELECT users.*, banned.username IS NOT NULL AS isBanned
FROM users LEFT JOIN banned ON users.username = banned.username

如果用户与banned表不匹配,则用户名(以及其他列)为NULL。您可以使用CASE WHEN来检查用户名是否为NULL

您还可以使用EXISTS代替LEFT JOIN来获取以下附加信息:

SELECT *, EXISTS(SELECT 1 FROM banned WHERE users.username = banned.username) AS isBanned
FROM users

还有使用IF的第三个选项:

SELECT users.*, IF(banned.username IS NULL, 0, 1) AS isBanned
FROM users LEFT JOIN banned ON users.username = banned.username

demo on dbfiddle.uk