简体   繁体   中英

Add data from second MySQL table to the result from the first one

I have 2 tables:

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

and

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

Is it possible to SELECT * FROM users and combine the result with the second table in order to find out if the user banned or not?

You can use the following using a 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

In case the user doesn't match to the banned table, the username (and the other columns too) is NULL . You can use a CASE WHEN to check if the username is NULL .

You can also use EXISTS instead of a LEFT JOIN to get this additional information:

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

And there is a third option using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM