Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 用于添加另一个表中缺少的行的Sql查询_Mysql_Sql - Fatal编程技术网

Mysql 用于添加另一个表中缺少的行的Sql查询

Mysql 用于添加另一个表中缺少的行的Sql查询,mysql,sql,Mysql,Sql,我有一个表a(列:id,年,月,金额)和表B(列:id,年,月,金额=0) 表A是主表,从2011年到2016年,每年每个月都有一组相同的ID 由于一些记录不存在(例如,他们的123456 id在03个月和2016年以及468976个数量方面没有记录),因此我想在表A中添加id为123456、03个月和2016年的新记录,由于缺少记录,因此金额将为0 缺失的记录取自表B,该表具有表A中相同的id集,对于2011年至2016年期间每年每月具有的每个id,每行金额为0 注: 1.表A中的记录未排序,

我有一个表a(列:id,年,月,金额)和表B(列:id,年,月,金额=0)

表A是主表,从2011年到2016年,每年每个月都有一组相同的ID

由于一些记录不存在(例如,他们的123456 id在03个月和2016年以及468976个数量方面没有记录),因此我想在表A中添加id为123456、03个月和2016年的新记录,由于缺少记录,因此金额将为0

缺失的记录取自表B,该表具有表A中相同的id集,对于2011年至2016年期间每年每月具有的每个id,每行金额为0

注: 1.表A中的记录未排序,表中的记录按id、年份和月份分组。 2.如果可能,请将其设置为普通sql查询,而不是pl/sql查询。如果不能如我所愿,请提出你的答案


提前感谢……。我希望您理解问题陈述。

您可以使用
交叉连接和一些其他逻辑生成记录:

select i.id, ym.year, ym.month
from (select distinct year, month from a) ym cross join
     (select distinct id from b) i left join
     a
     on a.year = ym.year and a.month = ym.month and b.id = i.id
where a.id is null;
(我想我的
a
s和
b
s是对的。我不确定为什么在问题中提到两个单独的表。似乎
a
缺少记录,所以它是唯一需要的表。我最好的猜测是
b
a
中ID的子集)

以下是执行插入操作的版本:

insert into a(id, year, month)
    select i.id, ym.year, ym.month
    from (select distinct year, month from b) ym cross join
         (select distinct id from b) i left join
         b
         on b.year = ym.year and b.month = ym.month and b.id = i.id
    where b.id is null;

See显示了如何编写一个查询来查找表a中不是表B的所有行。然后,您可以在
插入到表B中选择
查询来插入所有缺少的行。为了方便起见,我采用了使用表B的方法。现在我的问题是:如何在与上述结构相同的表a中添加缺少的行。我想检查一个id(在表a中,没有id存在金额、月份和年份为空的值,因此在插入id时也应注意),缺少哪个月份和年份,并插入金额为0的月份和年份。