我有一个结果集,我需要连接另一个表中的相关字段。
我有以下两个表。 第一个表“组件”保存有关组件的信息:
+----+-------+------------+-----------+
| 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”字段连接到此结果集,从而指定组件添加到系统的时间。
最佳答案
只需加入
具有所有必需条件的表即可。
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;
关于MySQL 将字段连接到结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750170/