在mysql中连接三张表A、B、C,并返回A中的共同点。

问题描述 投票:-1回答:2

我想把下面的三个表A、B、C连接起来,只返回表A的公共部分(阴影部分)。

A
-------
ID, Name

B
-------
ID, ORG

C
--------
ID, DEP

enter image description here

请谁提供简单的连接查询

mysql sql join
2个回答
1
投票

我知道你想从 aid 可以在任何一个 bc.

这听起来像两个 exists 子查询。

select a.*
from a
where 
    exists (select 1 from b where b.id = a.id)
    or exists (select 1 from c where c.id = a.id)

如果你还想从表b或表c中获取列,你可以使用两个 left joins 而不是 where 条件,确保至少有一个连接成功。

select a.*, b.org, c.dept
from a
left join b on b.id = a.id
left join c on c.id = a.id
where b.id is not null or c.id is not null

1
投票

你想要一个 left join 始于 A 然后再进行一些过滤。

select . . .
from a left join
     b
     on . . .  left join
     c
     on . . .
where b.? is not null or c.? is not null;

The ? 中使用的任一列。join或各表的主键。

© www.soinside.com 2019 - 2024. All rights reserved.