【问题标题】:Conditional insert query (Row count validation). (MYSQL)条件插入查询(行计数验证)。 (MYSQL)
【发布时间】:2014-09-11 09:55:30
【问题描述】:

我正在尝试编写一个查询来计算和比较两个不同数据库上两个表的行数。如果它们相等,则一条记录将作为“通过”插入到另一个表中,否则将导致“失败”。 我无法通过谷歌搜索找到任何答案...这是我的查询不起作用:

select
case when
((select count(1) from db1.transaction) = (select count(1) from db2.transaction))
then
insert into db3.validation (test_result) values ('pass')
else
insert into db3.validation (test_result) values ('fail')
end;

【问题讨论】:

  • 您不能在选择中插入。把它分开。使用过程作为外壳。

标签: mysql insert conditional


【解决方案1】:

您可以通过颠倒顺序来做到这一点。使用 select 选择值执行单个 insert

insert into db3.validation(test_result)
    select (case when t1.cnt1 = t2.cnt2 then 'pass' else 'fail' end)
    from (select count(1) as cnt1 from db1.transaction) t1 cross join
         (select count(1) as cnt2 from db2.transaction) t2;

请注意,我将子查询从 case 移动到 from 子句,只是因为我发现这样更容易阅读。如果您愿意,可以将它们保存在 case 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 2013-07-16
    • 2016-03-21
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2018-05-15
    相关资源
    最近更新 更多