我有一个结果集,我需要加入另一个表中的相关字段。
我有以下两张表。 第一个表“components”保存有关组件的信息:
+----+-------+------------+-----------+
| id | name | serial_num | model_num |
+----+-------+------------+-----------+
| 1 | comp1 | 0000 | AAAA |
| 2 | comp2 | 0001 | AAAB |
| 3 | comp1 | 0010 | AABA |
| 4 | comp2 | 0011 | AABB |
| 5 | comp3 | 0100 | ABAA |
| 6 | comp1 | 0101 | AAAA |
+----+-------+------------+-----------+
第二个表'componentLog'跟踪组件所属的系统:
+-------------+-----------+---------+---------+-------+
| action_date | component | system | action | notes |
+-------------+-----------+---------+---------+-------+
| 2010-01-01 | 1 | CZMIL01 | added | NULL |
| 2010-02-25 | 1 | CZMIL01 | removed | NULL |
| 2010-01-01 | 2 | CZMIL01 | added | NULL |
| 2010-02-03 | 2 | CZMIL01 | removed | NULL |
| 2010-02-03 | 2 | CZMIL02 | added | NULL |
| 2010-01-14 | 3 | CZMIL02 | added | NULL |
| 2010-01-14 | 4 | CZMIL02 | added | NULL |
| 2010-02-03 | 4 | CZMIL02 | removed | NULL |
| 2010-02-03 | 4 | CZMIL01 | added | NULL |
| 2010-01-14 | 5 | CZMIL02 | added | NULL |
| 2010-02-25 | 6 | CZMIL01 | added | NULL |
+-------------+-----------+---------+---------+-------+
我有一个查询,告诉我在指定日期指定系统中有哪些组件:
SELECT *
FROM components
WHERE id IN (
SELECT component
FROM componentLog
WHERE action_date <= '2010-02-25'
AND system = 'CZMIL01'
)
AND id NOT IN (
SELECT component
FROM componentLog
WHERE action_date <= '2010-02-25'
AND system = 'CZMIL01'
AND action = 'removed'
)
ORDER BY name;
此查询提供以下结果集:
+----+-------+------------+-----------+
| id | name | serial_num | model_num |
+----+-------+------------+-----------+
| 6 | comp1 | 0101 | AAAA |
| 4 | comp2 | 0011 | AABB |
+----+-------+------------+-----------+
我需要的是将'componentLog'表中的'action_date'字段加入到此结果集中,从而指定何时将组件添加到系统中。
答案 0 :(得分:2)
只需join
具有所有必要条件的表格。
SELECT c.*,cl.action_date
FROM components c
JOIN componentLog cl on c.id = cl.component
WHERE action_date <= '2010-02-25'
AND system = 'CZMIL01'
AND action <> 'removed'
ORDER BY name;
如果需要从结果中排除对给定系统至少有一个removed
操作的组件,请使用
select t.*, cl.action_date
from (
select * from components c
where not exists (select 1 from componentlog
where component = c.id and action = 'removed'
and system = 'CZMIL01' and action_date <= '2010-02-25')
) t
join componentLog cl on cl.component = t.id
WHERE system = 'CZMIL01' and action_date <= '2010-02-25'
ORDER BY name;