如何根据不同的 table 在 table 中插入行?
How to insert rows in a table depending on a different table?
我有两个 table。
一个 user
table 包含 user_id、user_email、user_name
和其他 user_status
table 包含 user_email,状态。
我面临的问题是 user_status
table 是新添加的,它是空的。 user
table 已经在制作中了。我想实现一个场景,我可以在 status
table 中添加行而无需清理数据库。
如果 user_name
为空,则 user_status
table 中的 status
将是 offline
否则 online
。
user_id user_email user_name
1 xyz@gmail.com xyz
2 abc@gmail.com
如果这是我的 user
table 而我的 user_status
table 是空的,那么我想更新 user_status
table如:
user_email status
xyz@gmail.com active
abc@gmail.com inactive
使用insert ...select
和一个条件表达式:
insert into user_status(user_email, status)
select user_email, case when user_name is null then 'offline' else 'online' end
from users
这假设您所说的“空”是指 null
。如果你真的是想空字符串,那么case
中的条件应该是where user_name = ''
。
请注意,user
是几乎所有数据库中的语言关键字,因此不是列名的好选择。我在查询中将其重命名为 users
。
我有两个 table。
一个 user
table 包含 user_id、user_email、user_name
和其他 user_status
table 包含 user_email,状态。
我面临的问题是 user_status
table 是新添加的,它是空的。 user
table 已经在制作中了。我想实现一个场景,我可以在 status
table 中添加行而无需清理数据库。
如果 user_name
为空,则 user_status
table 中的 status
将是 offline
否则 online
。
user_id user_email user_name
1 xyz@gmail.com xyz
2 abc@gmail.com
如果这是我的 user
table 而我的 user_status
table 是空的,那么我想更新 user_status
table如:
user_email status
xyz@gmail.com active
abc@gmail.com inactive
使用insert ...select
和一个条件表达式:
insert into user_status(user_email, status)
select user_email, case when user_name is null then 'offline' else 'online' end
from users
这假设您所说的“空”是指 null
。如果你真的是想空字符串,那么case
中的条件应该是where user_name = ''
。
请注意,user
是几乎所有数据库中的语言关键字,因此不是列名的好选择。我在查询中将其重命名为 users
。