在 WHERE 子句中使用 IN 语句时保持排序顺序

发布于 2024-11-08 18:30:19 字数 428 浏览 6 评论 0原文

我使用的是 SQL Server 2005。

我有一个临时排序表 (Table_A),其中包含 2 列(IDRowNumber)。
现在,我通过选择临时表 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

咋地 2024-11-15 18:30:19

您需要改用JOIN。下面我假设 Table_A 每个 ID 只能有 1 行。如果情况并非如此,则重写为 JOIN 将引入重复行,并且我们需要更多详细信息来了解在这种情况下用于排序目的的 RowNumber

SELECT Table_B.* 
FROM Table_B JOIN Table_A ON  Table_B.ID = Table_A.ID
ORDER BY Table_A.RowNumber

You'll need to use a JOIN instead. I have assumed below that Table_A can only have 1 row per ID. If this is not the case then rewriting as a JOIN will introduce duplicate rows and we will need more details of which RowNumber to use for sorting purposes in that case.

SELECT Table_B.* 
FROM Table_B JOIN Table_A ON  Table_B.ID = Table_A.ID
ORDER BY Table_A.RowNumber
洒一地阳光 2024-11-15 18:30:19

从 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文