我有一个 sqllite 表;
CREATE TABLE tmp2(
id INT,
account TEXT,
name TEXT,
)
我的表(表 tmp2)看起来像:
id , account , name
1 A1 bob
2 A2 dave,john,sally
3 A3 tom
我需要创建一个新表(表 B),以便只有 1 个名称/行:
id , account , name
1 A1 bob
2 A2 dave
2 A2 john
2 A2 sally
3 A3 tom
复制所有其他字段。鉴于主键不能重复,这可能使用 sql 吗?还使用 sql 如何访问 "dave, john, sally"中的个人姓名?
最佳答案
这是一个 SQLite 解决方案(基于 MCVE,如本答案末尾所示)。
with singles(id, account, first, rest) as
UNION ALL
的substr(name, 0, instr(name||', ', ', '))
substr(name, instr(name||', ', ', ')+2)
select id, account, first from singles
order by id
, .separator ' '
代码:
with singles(id, account, first, rest) as
( select id,
account,
substr(name, 0, instr(name||', ', ', ')),
substr(name, instr(name||', ', ', ')+2)
from tmp2
UNION
select id,
account,
substr(rest, 0, instr(rest||', ', ', ')),
substr(rest, instr(rest||', ', ', ')+2)
from singles where rest!=''
)
select id, account, first
from singles
order by id;
输出(带有
.separator ' '
):1 A1 Bob
2 A2 dave
2 A2 john
2 A2 sally
3 A3 tom
MCVE(对不起,小写首字母错别字...):
BEGIN TRANSACTION;
CREATE TABLE tmp2(
id INT,
account TEXT,
name TEXT);
INSERT INTO tmp2 VALUES(1,'A1','Bob');
INSERT INTO tmp2 VALUES(2,'A2','dave, john, sally');
INSERT INTO tmp2 VALUES(3,'A3','tom');
COMMIT;
在 Windows 10 上使用 SQLite 3.18.0 2017-03-28 18:48:43
如果您对使用 SQLite 的递归 CTE 感兴趣,我推荐这个,这是我对它们的知识来源:
https://sqlite.org/lang_with.html
顺便说一句,我同意 Joey Pinto 的观点,使用一个像样的数据库结构会更好......
关于Sqlite:基于非主键字段创建具有重复行的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45195831/