【问题标题】:inner join and union all using order by内部连接和联合都使用 order by
【发布时间】:2013-11-26 10:49:38
【问题描述】:

我有这个问题:

SELECT B.IMAGE_ID as image_id_fav,I.Image_Path as image_path_fav 
FROM Buddies B
INNER JOIN @favDT F ON F.favorite_id = B.Reg_ID and b.favorite_id=@regID 
INNER JOIN Images I ON I.Image_ID = B.Image_ID
where b.Image_ID >0 
union all
select I.image_id as image_id_fav,I.Image_Path as image_path_fav FROM Buddies B
inner join @favDT F ON F.favorite_id = B.Reg_ID and b.favorite_id=@regID
inner join registration  R on R.Reg_ID = F.favorite_id
INNER JOIN Images I ON R.Default_Image = I.Image_ID
WHERE B.Image_ID=0
union all
SELECT I.IMAGE_ID as image_id_fav, I.IMAGE_PATH as image_path_fav FROM @favDT F
 LEFT OUTER JOIN Buddies B ON B.Reg_ID = F.favorite_id and b.favorite_id=@regID
INNER JOIN registration  R on R.Reg_ID =F.favorite_id
     INNER JOIN Images I ON R.Default_Image = I.Image_ID
     WHERE B.Reg_ID IS NULL

我需要按 F.favorite_id 排序,但我在关键字 union all 附近不断收到不正确的语法

【问题讨论】:

  • 在查询结束时使用 order by 子句

标签: sql sql-server join sql-order-by union-all


【解决方案1】:

当您使用 UNION 时,您不能对单个查询进行排序并期望它按您想要的顺序返回。但是您可以在最后添加订单。 在您的情况下,您尝试按您未选择的列排序。

您可以简单地将 favorite_id 添加到每个选择中,然后添加一个外部查询,该查询只返回您想要的两个列,但按 favorite_id 排序:

SELECT image_id_fav,image_path_fav
FROM (
select B.IMAGE_ID as image_id_fav, I.Image_Path as image_path_fav, 
       F.favorite_id as FavID
from Buddies B
inner join @favDT F on F.favorite_id = B.Reg_ID and b.favorite_id = @regID
inner join Images I on I.Image_ID = B.Image_ID
where b.Image_ID > 0
union all
select I.image_id as image_id_fav, I.Image_Path as image_path_fav, 
       F.favorite_id
from Buddies B
inner join @favDT F on F.favorite_id = B.Reg_ID and b.favorite_id = @regID
inner join registration R on R.Reg_ID = F.favorite_id
inner join Images I on R.Default_Image = I.Image_ID
where B.Image_ID = 0
union all
select I.IMAGE_ID as image_id_fav, I.IMAGE_PATH as image_path_fav, 
       F.favorite_id
from @favDT F
left outer join Buddies B on B.Reg_ID = F.favorite_id and b.favorite_id = @regID
inner join registration R on R.Reg_ID = F.favorite_id
inner join Images I on R.Default_Image = I.Image_ID
where B.Reg_ID is null
)
ORDER BY FavID

【讨论】:

    【解决方案2】:

    Union All 构造中,您不能独立地对每个语句进行排序。您必须将ORDER BY 子句放在完整查询的末尾。

    这里有详细解释:

    ORDER BY in UNION ALL

    因此,您必须首先在 SELECT 列表中包含 F.favourite_id 列,然后它才会在最后一个 ORDER BY 子句中可见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2012-08-06
      • 1970-01-01
      • 2012-03-10
      相关资源
      最近更新 更多