MySQL Union - 首先从union中的第一个表中选择数据

时间:2015-02-19 12:13:07

标签: mysql sql

SELECT service.*
FROM star_service
INNER JOIN service ON service.code = star_service.service

UNION

SELECT service.*
FROM service

如何修改上述查询,以便首先显示第一个表的结果,然后显示联合中的第二个查询?

4 个答案:

答案 0 :(得分:6)

在结果集中添加一个附加列,然后使用该列进行排序。

像这样:

SELECT service.*, 1 as OBCol
FROM star_service
INNER JOIN service ON service.code = star_service.service

UNION

SELECT service.*, 2 as OBCol
FROM service

ORDER BY OBCol

答案 1 :(得分:2)

我会完全跳过union。如果您希望service中的所有内容与star_service中的所有内容一起使用,那么只需使用left joinorder by

select s.*
from service s left join
     star_service ss
     on s.code = ss.service
order by (ss.service is not null) desc;

编辑:

如果star_service中有重复项,那么最好使用exists

select s.*, (exists (select 1 from start_service ss where s.code = ss.service) ) as in_ss
from service s
order by (is_ss is not null) desc;

这些版本(带有正确的索引)应该比原始版本或union的任何版本都要好得多。

答案 2 :(得分:0)

使用UNION ALL,它会按照编码顺序保留两个查询结果的选定顺序(并保留重复项)。

只需添加ALL

SELECT service.*
FROM star_service
INNER JOIN service ON service.code = star_service.service

UNION ALL

SELECT service.*
FROM service

答案 3 :(得分:0)

最好使用UNION ALL代替UNION,因为

union给出了排序输出。

union all提供未排序的输出

SELECT service.*
FROM star_service
INNER JOIN service ON service.code = star_service.service

UNION ALL

SELECT service.*
FROM service
相关问题