将这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 :(得分:3)
尝试:
SELECT shipID, atime, null ltime from arrive
UNION ALL
SELECT shipID, null atime, ltime from `leave`
order by coalesce(atime,ltime)
SQLFiddle here。
答案 1 :(得分: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 |
答案 2 :(得分: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 :(得分: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 强>