使用 select 插入或更新并覆盖空值
Insert or update with select and override nulls
我有两个表:defaults 和 users 具有相同的列,除了 defaults user_id 列是唯一的,而在 "users" 中则不是。
我想从 users 中获取所有行并将它们插入到 defaults,如果 users 中的两行相同 user_id,我想以这样的方式合并它们,即所有 empty/null 值都将被非 empty/null 值覆盖
这是一个例子
users
-----
user_id|name|email|address
--------------------------
1 |abc |null |J St
1 |coco|a@b.c|null
插入默认值后,我希望得到下一个结果:
defaults
-----
user_id|name|email|address
--------------------------
1 |abc |a@b.c|J St
@Eric B 提供了 answer 如何使用插入值执行此操作:
Assuming 3 columns in the table.. ID, NAME, ROLE
This will update 2 of
the columns. When ID=1 exists, the ROLE will be unaffected. When ID=1
does not exist, the role will be set to 'Benchwarmer' instead of the
default value.
INSERT OR REPLACE INTO Employee (id, name, role)
VALUES ( 1,
'Susan Bar',
COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer')
);
当我使用 select 插入时如何执行此操作
insert or replace into defaults select ??? from users
INSERT OR REPLACE INT DEFAULTS VALUES (ID, Name, Role)
(
SELECT ID, MAX(Name), MAX(Role) FROM Users GROUP BY ID
);
最大值将 select 最大值而不是空值(如果有的话)。
我有两个表:defaults 和 users 具有相同的列,除了 defaults user_id 列是唯一的,而在 "users" 中则不是。
我想从 users 中获取所有行并将它们插入到 defaults,如果 users 中的两行相同 user_id,我想以这样的方式合并它们,即所有 empty/null 值都将被非 empty/null 值覆盖
这是一个例子
users
-----
user_id|name|email|address
--------------------------
1 |abc |null |J St
1 |coco|a@b.c|null
插入默认值后,我希望得到下一个结果:
defaults
-----
user_id|name|email|address
--------------------------
1 |abc |a@b.c|J St
@Eric B 提供了 answer 如何使用插入值执行此操作:
Assuming 3 columns in the table.. ID, NAME, ROLE
This will update 2 of the columns. When ID=1 exists, the ROLE will be unaffected. When ID=1 does not exist, the role will be set to 'Benchwarmer' instead of the default value.
INSERT OR REPLACE INTO Employee (id, name, role)
VALUES ( 1,
'Susan Bar',
COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer')
);
当我使用 select 插入时如何执行此操作
insert or replace into defaults select ??? from users
INSERT OR REPLACE INT DEFAULTS VALUES (ID, Name, Role)
(
SELECT ID, MAX(Name), MAX(Role) FROM Users GROUP BY ID
);
最大值将 select 最大值而不是空值(如果有的话)。