mysql插入类别行

oyjwcjzk  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(306)

我正在努力描述标题中的问题,更不用说寻找一个很可能存在的解决方案,所以请原谅,或指向我的线程。我需要填充行,因此在下面的简化场景中,每个类别有4行:

mysql> select * from a;
+-------+
|  Num  |
+-------+
|     1 |
|     2 |
|     3 |
|     4 |
+-------+
mysql> select * from b;
+----------+------+------+
| Category | Num  | Data |
+----------+------+------+
| X        |    2 |   10 |
| X        |    3 |   12 |
| X        |    4 |    8 |
| Y        |    1 |    0 |
| Y        |    2 |   19 |
| y        |    3 |   15 |
| y        |    4 |   22 |
| Z        |    2 |   10 |
+----------+------+------+

我需要的结果总是每个类别4行(表b总是有num=1、2、3或4中的一个),为填充行设置data=null:

mysql> select * from c;
+----------+------+------+
| Category | Num  | Data |
+----------+------+------+
| X        |    1 | NULL |
| X        |    2 |   10 |
| X        |    3 |   12 |
| X        |    4 |    8 |
| Y        |    1 |    0 |
| Y        |    2 |   19 |
| y        |    3 |   15 |
| y        |    4 |   22 |
| Z        |    1 | NULL |
| Z        |    2 |   10 |
| Z        |    3 | NULL |
| Z        |    4 | NULL |
+----------+------+------+

我人为地创建了一个表,因为我认为它可能有助于(插入)查询?!

fwzugrvs

fwzugrvs1#

你可以 cross joina 表中包含所有可用类别 b ,然后把table拿来 b 用一个 left join .

select 
    c.category,
    a.num,
    b.data
from a
cross join (select distinct category from b) c
left join b on b.category = c.category and b.num = a.num

你可以很容易地把它变成一个 insert 查询到另一个表:

insert into c(category, num, data)
select 
    c.category,
    a.num,
    b.data
from a
cross join (select distinct category from b) c
left join b on b.category = c.category and b.num = a.num
az31mfrm

az31mfrm2#

你需要左键连接

select a.num, b.category , b.data
from tablea a
left join tableb b on a.num = b.num

用于插入

insert into tablec (num, category, data)
select a.num, b.category , b.data
from tablea a
left join tableb b on a.num = b.num

如果需要更新现有行

update tablec c
inner join ( 
select a.num, b.category , ifnull(b.data,0)
from tablea a
left join tableb b on a.num = b.num ) t t.num= c.num  and t.category = c.category
set data  = t.data

相关问题