SQL - Check if record exists in multiple tables

大城市里の小女人 提交于 2020-04-16 08:28:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!