SQL - 如何在 Mysql 中插入来自另一个 table 的附加到 Id 的新行
SQL - how to insert new rows attached to Id from another table in Mysql
在这种情况下,我在 MySql 数据库中有两个 table。第一个是 User 实体,第二个实体是 Notification。这些实体在结构上是相关的。
通知实体如下所示:
id newsletter type user_id
1 0 EMAIL 5
2 1 SMS 5
3 1 FACEBOOK 5
4 1 EMAIL 7
5 0 SMS 7
6 0 FACEBOOK 7
sql 语句应该如何为每个 user_id
插入新行
我试过这样的事情,或者首先从这个 table 中获取所有用户,并为每个迭代和插入值。
INSERT INTO db.notification (newsletter, type, user_id) select true, 'GOOGLE', user_id foreach existing user from db.notification
所以输出看起来像:
id newsletter type user_id
1 0 EMAIL 5
2 1 SMS 5
3 1 FACEBOOK 5
4 1 EMAIL 7
5 0 SMS 7
6 0 FACEBOOK 7
7 1 GOOGLE 5
8 1 GOOGLE 7
您可以使用 insert . . . select
:
INSERT INTO db.notification (newsletter, type, user_id)
select distinct true, 'GOOGLE', user_id
from db.notification ;
在这种情况下,我在 MySql 数据库中有两个 table。第一个是 User 实体,第二个实体是 Notification。这些实体在结构上是相关的。
通知实体如下所示:
id newsletter type user_id
1 0 EMAIL 5
2 1 SMS 5
3 1 FACEBOOK 5
4 1 EMAIL 7
5 0 SMS 7
6 0 FACEBOOK 7
sql 语句应该如何为每个 user_id
插入新行我试过这样的事情,或者首先从这个 table 中获取所有用户,并为每个迭代和插入值。
INSERT INTO db.notification (newsletter, type, user_id) select true, 'GOOGLE', user_id foreach existing user from db.notification
所以输出看起来像:
id newsletter type user_id
1 0 EMAIL 5
2 1 SMS 5
3 1 FACEBOOK 5
4 1 EMAIL 7
5 0 SMS 7
6 0 FACEBOOK 7
7 1 GOOGLE 5
8 1 GOOGLE 7
您可以使用 insert . . . select
:
INSERT INTO db.notification (newsletter, type, user_id)
select distinct true, 'GOOGLE', user_id
from db.notification ;