在 WHERE 子句中使用 IN 语句时保持排序顺序
我使用的是 SQL Server 2005。
我有一个临时排序表 (Table_A
),其中包含 2 列(ID
、RowNumber
)。
现在,我通过选择临时表 (Table_A
) 中存在(ID
值)的其他表 (Table_B
) 中的所有行来创建一个新表)。
SELECT *
FROM Table_B
WHERE Table_B.ID IN (SELECT ID FROM Table_A)
上面查询的结果未按 Table_A
排序。
我正在寻找一种方法来保持新结果表的结果按 Table_A
排序。
德克萨斯....
I'm using SQL Server 2005.
I have a temporary sorted table (Table_A
) that contains 2 columns (ID
, RowNumber
).
Now, I create a new table by selecting all rows from other table (Table_B
) that exist (ID
value) in the temporary table (Table_A
).
SELECT *
FROM Table_B
WHERE Table_B.ID IN (SELECT ID FROM Table_A)
The results of the query above is not sorted by Table_A
sorting.
I'm looking for a way to keep the results of the new result table sorted by the Table_A
sorting.
Tx....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要改用
JOIN
。下面我假设Table_A
每个ID
只能有 1 行。如果情况并非如此,则重写为JOIN
将引入重复行,并且我们需要更多详细信息来了解在这种情况下用于排序目的的RowNumber
。You'll need to use a
JOIN
instead. I have assumed below thatTable_A
can only have 1 row perID
. If this is not the case then rewriting as aJOIN
will introduce duplicate rows and we will need more details of whichRowNumber
to use for sorting purposes in that case.从 Table_B b 中选择 b.*
在 a.id = b.id 上加入 Table_A a
按 a.RowNumber 排序
select b.* from Table_B b
join Table_A a on a.id = b.id
order by a.RowNumber