我的问题如下:
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
时,查询可以正常运行。
答案 0 :(得分:1)
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
答案 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;