我一直在堆栈中搜索类似的问题,但我找不到一个帮助我解决这个问题,或者我无法理解它。 我有3张桌子。
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 |
+---------+------+--------------+
我正在尝试进行查询,以了解City1和City2表中是否存在特定的id_user。我真的不知道如何构建它。例如,完成id_user = user1,我想收到类似city1 = true,city2 = true的内容。 (在两个表中,user1都存在);或者完成id_user = 2,收到city1 = true,city2 = false。
有关如何做到的任何想法?
非常感谢
答案 0 :(得分:5)
如果每个表中没有重复用户ID,则可以使用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;
如果您只想查看一个用户的信息,可以添加where
子句。