【问题标题】:How to insert rows in a table depending on a different table?如何根据不同的表在表中插入行?
【发布时间】:2020-07-30 16:28:39
【问题描述】:

我有两张桌子。 一个包含 user_id、user_email、user_name 的 user
和其他包含 user_email、状态的 user_status 表。
我面临的问题是 user_status 表是新添加的,它是空的。 user 表已经在生产中。我想实现一个场景,我可以在status 表中添加行而不清理数据库。

如果user_name 为空,则user_status 表中的status 将为offline,否则为online

user_id    user_email    user_name   
1          xyz@gmail.com   xyz       
2          abc@gmail.com             

如果这是我的user 表并且我的user_status 表是空的,那么我想将user_status 表更新为:

user_email         status    
xyz@gmail.com      active    
abc@gmail.com      inactive  

【问题讨论】:

  • MySQL SQL Server Oracle Postgres。请不要向数据库标签发送垃圾邮件,只标记您正在使用的一个数据库。

标签: sql database case sql-insert


【解决方案1】:

使用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

【讨论】:

  • 是的,大多数数据库都有 user 作为保留关键字,但例如 MySQL 没有。见en.wikipedia.org/wiki/SQL_reserved_words
  • @jarlh:在 MySQL 中它不是保留字,但它是 a keyword - 所以对于表名来说仍然不是一个很好的选择。
  • 感谢您的回答。实际上这只是一个例子,所以我使用了user
猜你喜欢
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2023-03-09
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多