如何基于tableb记录行在tablea中插入多个记录?

igsr9ssn  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(294)

我有a表和b表below:-
表a

user_id|sub_category_id|category_id|is_removed
5      |201            |2          |false

表b

sub_category_id|category_id
101            |1
102            |1
103            |1
201            |2

如果category\u id为1,user\u id为5,is\u removed为false,我可以知道如何在表b的基础上向表a插入多条记录吗?谢谢您。

omqzjyyz

omqzjyyz1#

简短回答:
考虑到所描述的两个表:

insert into A (select 5, sub_category_id, category_id, false from B where category_id = 1);

详细说明:
a内容:

select * from A;
+---------+-----------------+-------------+------------+
| user_id | sub_category_id | category_id | is_removed |
+---------+-----------------+-------------+------------+
|       5 |             201 |           2 |          0 |
+---------+-----------------+-------------+------------+

b内容:

select * from B;
+-----------------+-------------+
| sub_category_id | category_id |
+-----------------+-------------+
|             101 |           1 |
|             102 |           1 |
|             103 |           1 |
|             201 |           2 |
+-----------------+-------------+

创建视图:

select 5, sub_category_id, category_id, false from B where category_id = 1;
+---+-----------------+-------------+-------+
| 5 | sub_category_id | category_id | FALSE |
+---+-----------------+-------------+-------+
| 5 |             101 |           1 |     0 |
| 5 |             102 |           1 |     0 |
| 5 |             103 |           1 |     0 |
+---+-----------------+-------------+-------+

插入:

insert into A (select 5, sub_category_id, category_id, false from B where category_id = 1);
+---------+-----------------+-------------+------------+
| user_id | sub_category_id | category_id | is_removed |
+---------+-----------------+-------------+------------+
|       5 |             201 |           2 |          0 |
|       5 |             101 |           1 |          0 |
|       5 |             102 |           1 |          0 |
|       5 |             103 |           1 |          0 |
+---------+-----------------+-------------+------------+

相关问题