我有2张桌子:
+-----------+
| users |
+-----------+
| John |
| Peter |
| Alex |
+-----------+
和
+-----------+
| banned |
+-----------+
| John |
| Peter |
+-----------+
是否可以SELECT * FROM users
并将结果与第二张表合并,以找出用户是否被禁止?
答案 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