2016-06-10 108 views
0

我有一個結果集,我需要從另一個表中加入相關的字段。MySQL連接字段結果集

我有以下兩張表。 第一個表,「部件」,保持有關組件信息:

+----+-------+------------+-----------+ 
| 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'字段到這個結果集,從而指定何時將組件添加到系統中。

回答

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; 

如果對於給定的系統ATLEAST一個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; 
+0

檢查編輯過的版本。 –

+0

感謝您的回覆! 它看起來像第二個查詢是在正確的軌道上。但是,給定的組件可能會在不同的方程中多次添加和刪除系統。所以我不能僅僅在組件被刪除的情況下排除組件。 「已刪除」操作必須在適當的時間間隔內。 – user6431631

+0

您可以將'action_date somedate'條件添加到'exists'來處理它。查詢修改,以包括該。 –