Mysql ORDER BY子句不适用于所有工会

Mysql ORDER BY子句不适用于所有工会,mysql,sql,sql-order-by,union,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抛出以下错误: “order子句”中的未知列“time” 当我删除,“dossier”作为源代码和,“contract”作为源代码时,查询工作正常。order by子句应用于此处

我的问题如下:

SELECT title, 'dossier' as Source FROM dossier  
UNION ALL 
SELECT title, 'contract' as Source FROM contract ORDER BY `time` LIMIT 5
time
列出现在两个表中,但MySQL抛出以下错误:

“order子句”中的未知列“time”


当我删除
,“dossier”作为源代码和
,“contract”作为源代码时,查询工作正常。

order by
子句应用于此处的
union all
总体选择,它没有
time
列(仅
title
Source
)。您可以使用临时表:

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

@钾肥有一种方法可以解决这个问题

您应该了解,
orderby
不是
select
子句的一部分。它只知道要选择的列

另一个解决方案很简单。也就是说,只需在结果集中包含
时间
。如果使用括号,发生的情况可能更清楚:

(SELECT title, 'dossier', time as Source
 FROM dossier  
)
UNION ALL 
(SELECT title, 'contract', time as Source
 FROM contract
)
ORDER BY `time`
LIMIT 5;
我应该注意到,如果表很大,并且它们在
时间上有索引,那么以下可能更有效:

(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;

请给出两个表的模式