我有两个查询与UNION ALL
1相结合:
--Query 1
SELECT Flavor, Color
FROM Friends
--Query 2
SELECT Flavor,
(SELECT TOP 1 Color
FROM Rainbows
WHERE Rainbows.StrangerID = Strangers.StrangerID
ORDER BY Wavelength DESC
) AS Color
FROM Strangers
当然,两者都可以单独工作,但与 a 结合使用时UNION ALL
:
SELECT Flavor, Color
FROM Friends
UNION ALL
SELECT Flavor,
(SELECT TOP 1 Color
FROM Rainbows
WHERE Rainbows.StrangerID = Strangers.StrangerID
ORDER BY Wavelength DESC
) AS Color
FROM Strangers
查询失败并出现以下错误:
如果语句包含 UNION 运算符,则消息 104、级别 15、状态 1、行 3 ORDER BY 项必须出现在选择列表中。
如何在带有 UNION ALL 的语句中使用 ORDER BY?
可复制粘贴示例
CREATE TABLE Friends (Flavor int, Color int)
CREATE TABLE Strangers (Flavor int, StrangerID int)
CREATE TABLE Rainbows (StrangerID int, Color int, Wavelength int)
go
SELECT Flavor, Color
FROM Friends
UNION ALL
SELECT Flavor,
(SELECT TOP 1 Color
FROM Rainbows
WHERE Rainbows.StrangerID = Strangers.StrangerID
ORDER BY Wavelength DESC
) AS Color
FROM Strangers
go
DROP TABLE Rainbows
DROP TABLE Strangers
DROP TABLE Friends
服务器:如果语句包含 UNION 运算符,则消息 104、级别 15、状态 1、行 2 ORDER BY 项必须出现在选择列表中。
脚注
- 1人为的假设示例。或不。