请教 union all 问题

代码日志 2011-07-21 09:00:16
select top 1 id from tag where type=1 order by id desc
union all
select top 1 id from tag where type=0 order by id desc

比如这个语句,总是查询上面的数据是对的,如果把下面的语句放上面也能查询出来,
但是下面的语句就是不能递减排序,不知道怎么回事,请教下
...全文
88 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
代码日志 2011-07-21
  • 打赏
  • 举报
回复
明白,感谢楼上的
WWWWA 2011-07-21
  • 打赏
  • 举报
回复
You have to use the Order By at the end of ALL the unions。
the ORDER BY is considered to apply to the whole UNION result(it's effectively got lower binding priority than the UNION).
The ORDER BY clause just needs to be the last statement, after you've done all your unioning. You can union several sets together, then put an ORDER BY clause after the last set.
所以,只能在union的最后一个子查询中使用order by,而这个order by是针对整个unioning后的结果集的。So:
如果unoin的几个子查询列名不同,如
Sql代码
select supplier_id, supplier_name
from suppliers
UNION
select company_id, company_name
from companies
ORDER BY ?;

这里的问号如果是company_name,则执行整个查询会报“company_name:invalid identifier”(当然,单独执行第二个含order by的子查询是没有问题的);这是因为unioning后结果集的列名是以第一个参加union的子查询的列名为准的;order by针对的是整个unioning后的结果集。对整个查询结果来说,无”company_name“这个字段
如果是supplier_name,则单独执行第二个含order by的子查询是会报“supplier_name:invalid identifier”的,而执行整个查询是没有问题的,因为order by针对的是unioning后的整个结果集,而这“整个结果集”是有supplier_name这列的(以第一个union子查询的列名作为 unioning后整个结果集的列名)

为了避免这样事情的发生,可以:
1 使用列序号代替实际列名。如:
Sql代码
select supplier_id, supplier_name
from suppliers
UNION
select company_id, company_name
from companies
ORDER BY 2;

2 为unoin的各个子查询使用相同的列名,如:
Sql代码
select supplier_id as id, supplier_name as name
from suppliers
UNION
select company_id as id, company_name as name
from companies
ORDER BY name;
WWWWA 2011-07-21
  • 打赏
  • 举报
回复
分别取结果再UNION
代码日志 2011-07-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wwwwb 的回复:]
select * from (
select top 1 id from tag where type=1 order by id desc )
union all
select * from (
select top 1 id from tag where type=0 order by id desc)
[/Quote]

这个是可以 但是我的写法为什么不行呢?
wwwwb 2011-07-21
  • 打赏
  • 举报
回复
select * from (
select top 1 id from tag where type=1 order by id desc )
union all
select * from (
select top 1 id from tag where type=0 order by id desc)

7,712

社区成员

发帖
与我相关
我的任务
社区描述
Microsoft Office Access是由微软发布的关系数据库管理系统。它结合了 MicrosoftJet Database Engine 和 图形用户界面两项特点。
社区管理员
  • Access
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧