2013-05-28 175 views
4

Supose這些3個表:結合兩個表

SHIP:

ID     
-------------------- 

    1       
    2        
    3 

ARRIVE:

shipID  Atime 
-------------------- 
    1  t1 
    1  t3 

LEAVE:

shipID  Ltime 
-------------------- 
    1  t2 
    1  t4 

我需要返回的查詢:

shipID Atime Ltime 
------------------------------ 
    1  t1  null 
    1  null  t2 
    1  t3  null 
    1  null  t4 

其中T1> T2> T3> T4

這個結果是可以接受的:

shipID Atime Ltime 
------------------------------ 
    1  t1  null 
    1  t3  null 
    1  null  t2 
    1  null  t4 
+0

第2行原表的2船ID開始,但隨後到達,相應出貨ID離開(在同一行2)顯示1的船ID。是否正確? – lurker

+0

爲什麼在不同的行上?爲什麼不在同一行中有t1和t2? t3和t4也一樣。 – fancyPants

+0

這都是關於shipID = 1,2和3這裏沒關係 – teocka

回答

1

嘗試這種情況:

SELECT DISTINCT 
    t1.shipid, 
    a.atime, 
    l.ltime 
FROM 
(
    SELECT shipID, atime AS time from arrive 
    UNION ALL 
    SELECT shipID, ltime AS time from `leave` 
) AS t1 
LEFT JOIN arrive AS a ON a.shipid = t1.shipid AND a.atime = t1.time 
LEFT JOIN `leave` AS l ON l.shipid = t1.shipid AND l.ltime = t1.time 

看到它在這裏行動:

這會給你:

| SHIPID | ATIME | LTIME | 
---------------------------- 
|  1 |  t1 | (null) | 
|  1 |  t3 | (null) | 
|  1 | (null) |  t2 | 
|  1 | (null) |  t4 | 
+0

非常感謝。它可以正常工作 – teocka

+0

@ user2427945 - 隨時歡迎您:)如果您發現問題或任何答案,請嘗試接受答案:) –

1

基本上要通過交錯值順序由一個整列,那麼其他的...

反對排序
--Dummy Tables 
CREATE TABLE #ship (ID int) 
CREATE TABLE #arrive (ID int, atime DateTime) 
CREATE TABLE #leave (ID int, ltime DateTime) 

--Dummy Data 
INSERT INTO #ship (ID) values (1); 
INSERT INTO #arrive (ID, atime) VALUES (1, '2013-05-29 00:00:00') 
INSERT INTO #arrive (ID, atime) VALUES (1, '2013-05-29 12:00:00') 
INSERT INTO #leave (ID, ltime) VALUES (1, '2013-05-29 06:00:00') 
INSERT INTO #leave (ID, ltime) VALUES (1, '2013-05-29 18:00:00') 


SELECT 
    i.ID, 
    CASE WHEN i.label = 'l' then i.thetime else null end as atime, 
    CASE WHEN i.label = 'a' then i.thetime else null end as ltime 
FROM (
     SELECT 'l' as label,ID,atime as thetime FROM #arrive 
     UNION 
     SELECT 'a' as label,ID,ltime as thetime FROM #leave 
    ) as i 
ORDER BY i.thetime 

--Cleanup 
DROP TABLE #ship 
DROP TABLE #arrive 
DROP TABLE #leave 

結果在。

ID   atime     ltime 
----------- ----------------------- ----------------------- 
1   2013-05-29 00:00:00.000 NULL 
1   NULL     2013-05-29 06:00:00.000 
1   2013-05-29 12:00:00.000 NULL 
1   NULL     2013-05-29 18:00:00.000 
3

嘗試:

SELECT shipID, atime, null ltime from arrive 
UNION ALL 
SELECT shipID, null atime, ltime from `leave` 
order by coalesce(atime,ltime) 

SQLFiddle here

0

試試這個Query

select * from 
(select s.id as shipid,a.Atime as Atime,null as Ltime 
from Ship s 
inner join Arrival a on s.id=a.shipid 
union 
select s.id as shipid,null as Atime, l.Ltime as Ltime 
from Ship s 
left join Leave1 l on s.id=l.shipid)t 
where t.Atime is not null 
or t.Ltime is not null 

SQL Fiddle