gpt4 book ai didi

mysql - 根据插入情况对字符串进行排序

转载 作者:行者123 更新时间:2023-11-29 11:31:32 30 4
gpt4 key购买 nike

场景:我有一个包含单列(字符串)的表。我想检索按特定顺序存储的数据。

表 Tbl_EmployeeName 只有一列“姓名”

我通过下面的查询插入了记录

Insert Into Tbl_EmployeeName
select 'Z'
union
select 'y'
union
select 'x'
union
select 'w'
union
select 'v'
union
select 'u'
union
select 't'
union
select 's'

现在我希望这些记录的插入顺序相同。当我运行查询时:

select * from Tbl_EmployeeName 

它将按名称 asc 默认顺序排列记录。即

结果输出

s                                                
t
u
v
w
x
y
Z

我希望所有记录都这样

预期输出

z
y
x
w
v
u
t
s

您能否建议我是否有任何方法可以按正确的记录输入顺序获得此结果,并且无需向表中添加任何新列。

最佳答案

I inserted records through this below query

...query using union...

Now I want these records in the same order in which it is inserted.

令人惊讶的是,您按照插入的顺序检索记录。在 INSERT 上的每个 SELECT 语句之间使用 UNION 会导致记录在插入之前进行排序。 UNION 对所有结果执行固有的DISTINCT。将其切换为 UNION ALL 将消除固有的顺序。

但是...

Could you please suggest me is there any way to get this in proper sequence in which records are entered, and also without adding any new column to a table.

不幸的是,这是不可能的。 SQL 表表示无序集。它对于记录的顺序或记录的插入顺序没有原生概念。

When I run the query select * from Tbl_EmployeeName it will arrange the records in default order by Name asc.

这是错误的。如上所述,没有返回默认订单。执行该查询时获得的任何结果纯属巧合。如果不指定 ORDER BY 子句,则无法保证顺序。

Could you please suggest me is there any way to get this in proper sequence in which records are entered

与您的问题相反,您可以通过向表格添加新列来实现此目的。通过如下设置表:

Create Table Tbl_EmployeeName 
(
Id Int Identity(1,1) Not Null,
Name Varchar (10) -- Or whatever your size is
);

然后进行插入:

Insert  Tbl_EmployeeName 
(Name)
Values ('Z'),
('y'),
('x'),
('w'),
('v'),
('u'),
('t'),
('s')

并查询:

Select  Name
From Tbl_EmployeeName
Order By Id Asc

关于mysql - 根据插入情况对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330790/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com