我有一个在oracle中工作的select语句。这是对它的外观的模仿(实际语句是200多行):
select * from (
select * from (
select id, name from my_table where name like 'D%' or name like 'Z%' order by name, id)
union all
select * from (
select id, name from my_table where name like 'K%' or name like 'T%' order by name, id)
union all
select * from (
select id, name from my_table where name like 'B%' or name like 'M%' order by name, id)
);
所以,基本上,它是同一张表中3种类型的记录的并集。外部的“ select * from”将自动添加,并且无法删除/更改。顺序很重要-必须先记录第一个子查询中的记录,然后记录第二个子查询中的记录,等等。
我需要为sql server重写它(最好是一条同样适用于oracle和sql server的通用语句,但这是可选的)
我尝试过的是:
select * from (
select * from (
select id, name, 1 as order_column from my_table where name like 'D%' or name like 'Z%') subquery
union all
select * from (
select id, name, 2 as order_column from my_table where name like 'K%' or name like 'T%') subquery
union all
select * from (
select id, name, 3 as order_column from my_table where name like 'B%' or name like 'M%') subquery
) outerquery order by order_column, name, id;
顺序被保留,但是order_column包含在结果记录中,这是错误的。
所以我将其更改为:
select * from (
select id, name from (
select id, name, 1 as order_column from my_table where name like 'D%' or name like 'Z%') subquery
union all
select id, name from (
select id, name, 2 as order_column from my_table where name like 'K%' or name like 'T%') subquery
union all
select id, name from (
select id, name, 3 as order_column from my_table where name like 'B%' or name like 'M%') subquery
) parentquery order by order_column, name, id
但是现在,很明显,order_column在外部查询中不可见,并且不起作用。正如我在第一行中的“ select * from”之前所写的那样,无法更改-只能更改外部的ORDER BY子句。同样,示例条件“名称,例如'D%'”实际上要复杂得多,在...(它们必须留在子查询中)的情况下,我无法以某种外部顺序使用它们。
感谢您的帮助。
答案 0 :(得分:2)
两个数据库都不保证没有order by
的结果集的顺序。
为什么不只是在两个数据库中都这样做?
select id, name, 1 as order_column
from my_table
where name like 'D%' or name like 'Z%' or
name like 'K%' or name like 'T%' or
name like 'B%' or name like 'M%'
order by (case when name like 'D%' or name like 'Z%' then 1
when name like 'K%' or name like 'T%' then 2
when name like 'B%' or name like 'M%' then 3
end)
在SQL Server中,您可以将其简化为:
select id, name, 1 as order_column
from my_table
where name like '[DZKTBM]%'
order by (case when name like '[DZ]%' then 1
when name like '[KT]%' then 2
when name like '[BM]%' then 3
end)