2017-10-19 83 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;