2017-10-19 98 views
2

我的問題如下:ORDER BY子句不能與UNION工作的所有

SELECT title, 'dossier' as Source FROM dossier 
UNION ALL 
SELECT title, 'contract' as Source FROM contract ORDER BY `time` LIMIT 5 

time列存在兩個表中,但MySQL的引發以下錯誤:

unknown column 'time' in 'order clause'

當我刪除, 'dossier' as Source, 'contract' as Source查詢工作正常。

+1

請給作爲兩個表格的模式 – apomene

回答

1

order by子句在這裏的union all整體選擇應用,這不具有time欄目(僅titleSource)。你可以做的是使用臨時表:

select `title`, `source` from (
    select `title`, 'dossier' as `Source`, `time` from dossier 
    union all 
    select `title`, 'contract', `time` from contract 
) tbl 
order by `time` 
limit 5 
1

@Potashin有一個解決這個問題的方法。

您應該明白order by不是select子句的一部分。它只知道正在選擇的列。

另一個解決方案很簡單。 。 。那就是簡單地在結果集中包含time。這是怎麼回事,如果你使用括號可能會更清楚:

(SELECT title, 'dossier', time as Source 
FROM dossier 
) 
UNION ALL 
(SELECT title, 'contract', time as Source 
FROM contract 
) 
ORDER BY `time` 
LIMIT 5; 

我要指出的是,如果表很大,他們對time索引,那麼下面可能更爲有效:

(SELECT title, 'dossier', time as Source 
FROM dossier 
ORDER BY `time` 
LIMIT 5 
) 
UNION ALL 
(SELECT title, 'contract', time as Source 
FROM contract 
ORDER BY `time` 
LIMIT 5 
) 
ORDER BY `time` 
LIMIT 5;