mysql获取一个表到三个表的交集

时间:2014-05-17 01:34:45

标签: mysql

我有一个像这样的表结构:

units
+---------+---------+
|    id   |   unit  |
+---------+---------+
|    1    |   lbs   |
+---------+---------+
|    2    |   cm    |
+---------+---------+
|    3    |   lit   |
+---------+---------+
|    4    |   cum   |
+---------+---------+

material
+----+---------+--------------+
| id | unit_id | material_name|
+----+---------+--------------+
| 1  |    3    |      pcb     |
+----+---------+--------------+
| 2  |    4    |      lbc     |
+----+---------+--------------+

equipment
+----+---------+--------------+
| id | unit_id |equipment_name|
+----+---------+--------------+
| 1  |    1    |      ber     |
+----+---------+--------------+
| 2  |    4    |      war     |
+----+---------+--------------+

project_items
+----+---------+--------------+
| id | unit_id | project_name |
+----+---------+--------------+
| 1  |    1    |      sec     |
+----+---------+--------------+
| 2  |    3    |      dum     |
+----+---------+--------------+

我想只获得仅存在于其他3个表中的unit_id

enter image description here

我尝试使用内连接

SELECT u.id FROM  units u 
INNER JOIN material m ON u.id = m.unit_id
INNER JOIN equipment e ON u.id = e.unit_id
INNER JOIN project_items i ON u.id = i.unit_id;

但是这只选择在所有表格上相交的id,任何想法?

2 个答案:

答案 0 :(得分:1)

可能有很多方法可以做到这一点,但这可以像使用EXISTS一样简单,如下:

SELECT u.id 
FROM  units u 
WHERE EXISTS (
    SELECT * FROM material m
    WHERE  u.id=m.unit_id)
  OR EXISTS (
    SELECT * FROM equipment e
    WHERE  u.id=e.unit_id)
  OR EXISTS (
    SELECT * FROM project_items I
    WHERE  u.id = i.unit_id)

答案 1 :(得分:0)

以下使用INUNION ALL进行此操作的方法之一:

select *
from units
where id in (
  select unit_id from material
  union all
  select unit_id from equipment
  union all 
  select unit_id from project_items)