问题
I've been searching in stack for similiar questions but I couldn't find one that helps me with this issue, or I couldn't understand it. I've got 3 tables.
Users
+---------+------+--------------+
| id_user | name | age |
+---------+------+--------------+
| user1 | John | 51 |
+---------+------+--------------+
| user2 | Jane | 65 |
+---------+------+--------------+
| user3 | Katie| 51 |
+---------+------+--------------+
| user4 | Marck| 65 |
+---------+------+--------------+
City1
+---------+------+--------------+
| id_user | time | street |
+---------+------+--------------+
| user1 | 8 | 111111111111 |
+---------+------+--------------+
| user2 | 5 | 222222222222 |
+---------+------+--------------+
City2
+---------+------+--------------+
| user_id | time | street |
+---------+------+--------------+
| user1 | 6 | 111111111111 |
+---------+------+--------------+
| user4 | 7 | 222222222222 |
+---------+------+--------------+
I'm trying to do a query in order to know if a specific id_user exists in City1 and City2 tables. I don't really know how to strucuture it. For example, done id_user = user1, I would like to recieve something like city1 = true, city2=true. (in both tables, user1 exists); or done id_user=2, recieve city1=true, city2=false.
Any ideas of how to do that?
回答1:
If user ids are not repeated in each table, then you can use left outer join
:
select u.*,
(c1.id_user is not null) as InCity1,
(c2.id_user is not null) as InCity2
from users u left outer join
city1 c1
on u.id_user = c1.id_user left outer join
city2 c2
on u.id_user = c2.id_user;
You can add a where
clause if you want to see the information for only one user.
来源:https://stackoverflow.com/questions/21988328/sql-check-if-record-exists-in-multiple-tables