更新列表值SQLite
问题描述:
我有一个表。更新列表值SQLite
ID | VALUE
id_1 | 1, 2, 3, 4, 5
id_2 | 6, 7, 8, 9, 10
id_3 | 11, 12, 13, 14, 15
而且我通过值+ = 1需要变化值,最终的表应该是这样的:
ID | VALUE
id_1 | 2, 3, 4, 5, 6
id_2 | 7, 8, 9, 10, 11
id_3 | 12, 13, 14, 15, 16
我怎么能这样做?是否有可能用SQL查询做到这一点?我应该为VALUE
设置什么类型的数字或文字?
答
正如另一位用户所指出的,关系数据库最适合单列存储在列中的值。也就是说,你可以解析值(按分隔符分割),增加数字,将它们连接到一个字符串并更新该行。您需要为此创建一个自定义过程。见string functions和stored routines。
如果你必须这样做,你应该声明该列为TEXT或VARCHAR;上面显示的列表不能存储到数字列中。
完整答案是一些繁重的SQL编程问题。即使您提出了一个可行的解决方案,您的程序只能在一个数据库上运行的风险也相当可观。
所以:
更容易的方式是存储由独立的ID的二维数据行和位置:
id | pos | value
------------------
id_1 | 1 | 1
id_1 | 2 | 2
id_1 | 3 | 3
...
id_2 | 1 | 6
...
如果有另外的号码列表等领域进行特定的ID,创建另一个表,如上所示,其中id
是主表中的外键。
然后更新值仅仅是物质的发行
UPDATE table_name SET value = value + 1
答
解决方案与Python脚本:
db = sqlite3.connect('Database.db')
cursor = db.cursor()
cursor.execute('SELECT Value FROM Problems')
all_rows = cursor.fetchall()
for row in all_rows:
array = row[0].split(',')
new_string = ''
for id in array:
if (id != ''):
id = int(id)
id += 1
id = str(id)
new_string += id + ','
new_string = new_string[:-1]
cursor.execute('UPDATE Problems SET Value = ? WHERE Value = ?', (new_string, row[0]))
db.commit()
db.close
答
以下作品的更新:
create table t as
select 'id_1' id, '1, 2, 3, 4, 5' val union
select 'id_2' id, '6, 7, 8, 9, 10' val union
select 'id_3' id, '11, 12, 13, 14, 15' val;
update t set val=(
with
cnt(x) as (select 1 union all select x+1 from cnt limit 999),
split as (select id, x from t,cnt where instr(' '||val||',', ' '||x||',')>0)
select group_concat(x+1,', ') val from split where id=t.id
);
select * from t order by id;
结果:
id_1|2, 3, 4, 5, 6
id_2|7, 8, 9, 10, 11
id_3|12, 13, 14, 15, 16
它的工作原理,如果你的价值观是和1之间的整数给出的极限,在这个例子中设置为999。我在Sqlite版本3.11上成功测试了这个。
这是可能的,但它是非常困难的。像这样的问题就是为什么你不想在字符串属性中存储列表的完美例证。 – dasblinkenlight