ORDER BY子句不适用于UNION ALL

时间:2017-10-19 10:04:13

标签: mysql sql sql-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会引发以下错误:

  

未知专栏' time'在'订单条款'

当我删除, 'dossier' as Source, 'contract' as Source时,查询可以正常运行。

2 个答案:

答案 0 :(得分: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 :(得分: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;