1

有谁知道如何按特定列值将表中的记录插入另一个表顺序?

例如:

我有下表:

表A:

record_id int,
name varchar(100),
nickname(100),
chain_id int (PK),
chain_n int,
count int,
create_date datetime

表B:

record_id int,
name varchar(100),
nickname(100),
chain_id int (PK),
chain_n int,
create_date datetime

我对 tableA 有以下值:

record_id      name      nickname      chain_id      chain_n      count      create_date
1              Test      One           1             1            2          2013-06-06
2              Test      Two           2             1            5          2013-06-06
3              Test      Three         3             1            3          2013-06-06

我使用以下脚本将数据插入到 thableB

INSERT INTO tableB
(
    record_id,
    name,
    nickname,
    chain_id,
    chain_n,
    create_date
)
SELECT 
(
    record_id,
    name,
    nickname,
    chain_id,
    chain_n,
    create_date
)
FROM tableA
ORDER BY count DESC

我希望数据将插入到 tableB 中,如下所示:

record_id      name      nickname      chain_id      chain_n      create_date
2              Test      Two           2             1            2013-06-06
3              Test      Three         3             1            2013-06-06
1              Test      One           1             1            2013-06-06

但是,结果如下仍然按chain_id排序

record_id      name      nickname      chain_id      chain_n      create_date
1              Test      One           1             1            2013-06-06
2              Test      Two           2             1            2013-06-06
3              Test      Three         3             1            2013-06-06

有谁知道如何设法按计数插入记录顺序

4

2 回答 2

3

似乎 record_id 是您的主键,因此默认排序是由它完成的。这就是为什么您的输出与 tableA 中的相同。只需在 tableB 的 SELECT 子句中使用 ORDER BY。

于 2013-06-07T06:37:32.307 回答
2

Inserting records into a table in particular order doesn't make much sense to me becuase ORDER BY doesn't actually influence the way the data is written to your drive. All records will be inserted in the order of your clustered index. In any case if you want to query data from a table ordered by some field you should explicitly state it in the ORDER BY clause even if you want your data ordered by clustered index columns. Although all data is meant to be ordered by clustered index by default it's still up to SQL Server engine to define the best execution plan and change the order if required if you don't specify it explicitly in the ORDER BY clause.

于 2013-06-07T07:29:41.127 回答