查询排序问题

wxd_860825 2009-10-23 10:19:02
select a,b,c from t1 as tt1
inner join t2 as tt2 on tt1.a=tt2.a
order by tt2.d
union all

select a,b,c from.............




我要排序的字段不再查询范围之内,如何解决像这样的order by 和union all问题
...全文
113 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxd_860825 2009-10-23
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 xuejie09242 的回复:]
用union all 时,必须要在查询字段列表内。
[/Quote]


请给个例子,成功的例子最好
wxd_860825 2009-10-23
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 jia_guijun 的回复:]
SQL code;with tbas
(
[/Quote]


这句啥意思,总体意思不懂,请详解
wxd_860825 2009-10-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 fredrickhu 的回复:]
SQL codeselect a,b,cfrom t1as tt1innerjoin t2as tt2on tt1.a=tt2.aorderby (select dfrom t2)
[/Quote]


报错。服务器: 消息 116,级别 16,状态 1,行 1
当没有用 EXISTS 引入子查询时,在选择列表中只能指定一个表达式。
xuejie09242 2009-10-23
  • 打赏
  • 举报
回复
这是因为union all,单个查询排序是没有意义的,因为最后会综合形成一个结果。

如果你要特定顺序,必须添加一个字段了。
贾桂权 2009-10-23
  • 打赏
  • 举报
回复
;with tb as
(
select tt1.a,tt1.b,tt1.c,tt2.d from t1 as tt1
inner join t2 as tt2 on tt1.a=tt2.a
order by tt2.d
union all

select tt1.a,tt1.b,tt1.c,tt2.d from............. )

select a,b,c from tb order by d
wxd_860825 2009-10-23
  • 打赏
  • 举报
回复
union all上面的语句单独可以执行成功,下面的单独也可以成功。
就是连在一起时报错。
排序字段不会出现在查询之内
xuejie09242 2009-10-23
  • 打赏
  • 举报
回复
用union all 时,必须要在查询字段列表内。
--小F-- 2009-10-23
  • 打赏
  • 举报
回复
select a,b,c from t1 as tt1 
inner join t2 as tt2 on tt1.a=tt2.a
order by (select d from t2)

27,581

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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