这个有点像噩梦。我在一个现有数据库前端工作,我必须跳过箍以确保数据按正确的顺序显示。如果我能按Id排序的话,我的生活会简单得多,但是Id与数据几乎没有关联。
我的意思是
ID DATA
357 "7-1-5: Sensitive Information I can't share"
2521 "30-2-8-17: Yet more sensitive Information"
6002 "9-30: There's a 10 behind the colon, because I hate you"
8999 "2-2-4: This was populated in no particular order"
9001 "30-3: More Info."
我想这样订
ID DATA
0001 "2-2-4: This was populated in no particular order"
0002 "7-1-5: Sensitive Information I can't share"
0003 "9-30: There's a 10 behind the colon, because I hate you"
0004 "30-2-8-17: Yet more sensitive Information"
0005 "30-3: More Info."
基本上,我需要它按每一个1到2位数的数字排序,这些数字用破折号分隔,一次又一次,这样1-3就在1-2-1之后,1-1-50之后。
就像我一开始说的,我是一个前端的人,所以在MySql中执行东西比我一个人能做的还多。任何帮助都将不胜感激。
编辑:我刚刚意识到一个单独的表中有外键指向这个表,这让事情变得更糟。
最佳答案
尝试此查询:
SELECT col
FROM yourTable
ORDER BY SUBSTRING(col, INSTR(col, '"') + 1, INSTR(col, ':') - INSTR(col, '"') - 1)
SUBSTRING(...)
子句中的ORDER BY
项仅从文本中提取id。大概你想让他们从左到右按数字排序。即使它们是varchar,数字排序仍然可以工作。对于示例数据,这会产生以下输出:
ID 8999 DATA "2-2-4: This was populated in no particular order"
ID 2521 DATA "30-2-8-17: Yet more sensitive Information"
ID 357 DATA "7-1-5: Sensitive Information I can't share"
ID 6002 DATA "9-30: There's a 10 behind the colon, because I hate you"
Fiddle在编写这个答案时已经关闭,但是我在MySQL工作台中测试了这个查询,它看起来工作得很好。
编辑:
如果要为每个记录分配一个新的ID,可以创建一个新表(
newTable
),其中的ID列是自动递增的。然后可以使用INSERT INTO ... SELECT
和上面的ORDER BY
逻辑来填充表。ID字段应该由MySQL自动递增。INSERT INTO newTable (`id`, `col`)
SELECT NULL, col
FROM yourTable
ORDER BY SUBSTRING(col, INSTR(col, '"') + 1, INSTR(col, ':') - INSTR(col, '"') - 1)