SQLLITE将列及其数据从TableA移到TableB

时间:2019-05-24 15:21:42

标签: android sqlite android-sqlite database-migration android-room

我下面有两个表

带有列(id,table_bId,名称,地址,邮政编码,allowedPermisions)的table_a

带有列(id,类型,级别,信息)的table_b

我想创建一个迁移策略,因为我们现在应该将allowedPermissions数据存储在table_b中

这是我尝试过的:

UPDATE table_a, table_b
SET table_a.allowedPermissions = table_b.allowedPermissions 
WHERE table_b.id=table_a.table_bId;

在UPDATE table_a之后出现语法错误(在这里看到一个示例,您可以更新多个表吗?)

然后我尝试了另一种方法,方法是使用

创建新列allowedPermissions
ALTER TABLE table_b
ADD COLUMN allowedPermissions TEXT

但是如何将sq_a中table_a中的allowedPermissions内容复制到sqlite中的table_b中?

1 个答案:

答案 0 :(得分:0)

答案

我相信更新将是:-

UPDATE table_b SET allowedPermissions = (SELECT allowedPermisions FROM table_a WHERE table_a.table_bId = table_b.id);

其他

然后您可以使用:-

CREATE TABLE IF NOT EXISTS table_a_copy  AS  SELECT id, table_bId, name, address, postcode FROM table_a;
ALTER TABLE table_a RENAME TO table_a_old;
ALTER TABLE table_a_copy RENAME TO table_a;
DROP TABLE IF EXISTS table_a_old;

要从 table_a

中删除多余的 allowedPermisions

示例

请考虑以下演示:-

-- Create the original tables
DROP TABLE IF EXISTS table_a;
DROP TABLE IF EXISTS table_b;
CREATE TABLE IF NOT EXISTS table_a (id INTEGER PRIMARY KEY, table_bId INTEGER, name TEXT, address TEXT, postcode TEXT, allowedPermisions TEXT);
CREATE TABLE IF NOT EXISTS table_b (id INTEGER PRIMARY KEY, type TEXT, level INTEGER, info TEXT);

-- Populate the original tables
INSERT INTO table_b (type,level,info) VALUES
    ('TYEPA',1,'BLAH A'),('TYEPB',2,'BLAH B'),('TYEPC',1,'BLAH ')
;

INSERT INTO table_a (table_bId, name, address, postcode, allowedPermisions) VALUES
  (1,'Name A','ADDRESS A','OX120ND','READ'),
    (1,'Name M','ADDRESS M','SW050ND','READ'),
  (1,'Name X','ADDRESS X','FA120ND','READ'),
    (2,'Name Z','ADDRESS Z','OX120ND','WRITE')
;

-- Show what table_b looks like before the alter and update
SELECT * FROM table_b;

-- Alter an update table_b
ALTER TABLE table_b ADD COLUMN allowedPermissions;
UPDATE table_b SET allowedPermissions = (SELECT allowedPermisions FROM table_a WHERE table_a.table_bId = table_b.id);

-- Show what table_b looks like after the alter and update
SELECT * FROM table_b;

-- Clean up table_a (remove the allowdPermisions column)
DROP TABLE IF EXISTS table_a_copy;
CREATE TABLE IF NOT EXISTS table_a_copy  AS  SELECT id, table_bId, name, address, postcode FROM table_a;
ALTER TABLE table_a RENAME TO table_a_old;
ALTER TABLE table_a_copy RENAME TO table_a;
DROP TABLE IF EXISTS table_a_old;
SELECT * FROM table_a;

示例结果

第一个结果(更改和更新之前的table_b):-

enter image description here

第二个结果(更改和更新后的table_b):-

enter image description here

  • 第三行是一个孤立行(故意),因此为NULL

第三个结果(不包含allowedPermisions列的table_a):-

enter image description here