结合两个mysql查询返回ok而不是行

问题描述 投票:1回答:1

我有一个查询,其中我返回了一些关于发票的信息,我拿起那张发票并将其与另一张表“付款”进行比较,以查看该发票(fullamount -fullpaid)是否存在于另一个表中,如果它确实有某些功能不应该在我的后端代码中运行。

SELECT  a.status, a.rf_reference, a.payor_orig_id , a.gross_amount + a.type_related_amount as fullamount,
                    a.gross_paid + a.type_related_paid as fullpaid
            FROM    invoice a
            where   a.type = 3 and
                    a.status in (10, 30) and
                    a.UPDATE_DT is null
            having  fullamount > fullpaid
            order   by a.ORIG_ID;

上面的查询返回

status| rf_reference | payor_orig_id | fullamount | fullpaid
30        RF123456        212            1000         200

所以现在我将上面的信息传递给另一个查询以查看行字段是否匹配。

我这样传递它

select * 
from    payment 
where 
       payor_orig_id = 212 and
       rf_reference = RF123456 and
       payment_amount = (1000-200) and
       status = 10 and 
      INSERT_DT BETWEEN DATE_SUB(NOW(), INTERVAL 185 DAY) AND NOW() and
     UPDATE_DT IS NULL;

所以现在上面的代码将返回一行,基本上我不运行我的后端函数。

由于这是两个单独的查询,我想将它们组合到一个我确保添加having语句并检查在发票和付款表之间没有匹配的情况下返回ONLY行。

SELECT  a.status, a.rf_reference, a.payor_orig_id , a.gross_amount + a.type_related_amount as fullamount,
                a.gross_paid + a.type_related_paid as fullpaid,
                (select b.payment_amount 
                from    payment  b
                where 
                b.payor_orig_id = a.payor_orig_id and
                b.rf_reference = a.rf_reference and
                b.status = 10 and 
                b.INSERT_DT BETWEEN DATE_SUB(NOW(), INTERVAL 185 DAY) AND NOW() and
                b.UPDATE_DT IS NULL) as payment_amount
                FROM    invoice a
                where   a.type = 3 and
                        a.status in (10, 30) and
                        a.UPDATE_DT is null
                having  fullamount > fullpaid and 
                        (fullamount - fullpaid ) <> payment_amount
                order   by a.ORIG_ID;

上面的查询返回“OK”,这是奇怪的,因为我不知道如何调试它。

mysql
1个回答
1
投票

尝试使用NOT EXIST查看是否存在其他表

SELECT  a.* , 
    a.gross_amount + a.type_related_amount as fullamount,
    a.gross_paid + a.type_related_paid as fullpaid 
    FROM    invoice a
    where   a.type = 3 and
            a.status in (10, 30) and
            a.UPDATE_DT is null and 
            NOT EXISTS ( select * 
                    from    payment 
                    where 
                            payor_orig_id = a.payor_orig_id and
                            rf_reference = a.rf_reference and
                            payment_amount =  ((a.gross_amount + a.type_related_amount) - (a.gross_paid + a.type_related_paid)) and
                            status = 10 and 
                            INSERT_DT BETWEEN DATE_SUB(NOW(), INTERVAL 185 DAY) AND NOW() and
                            UPDATE_DT IS NULL ) 
            having  fullamount > fullpaid
            order   by a.ORIG_ID;
© www.soinside.com 2019 - 2024. All rights reserved.