我的问题很简单:我想列出“表单”表中的所有内容,如果“杰出”表中没有与此“表单”的任何匹配项,那么该行也应仅在表中用NULL列出。 PAYED_GROSS_AMOUNT列(例如,“未完成”表用于此列)。现在,通过此查询,我得到的只是“表单”匹配项,在“杰出”表中也具有匹配项:
SELECT
`f`.`ID` AS `ID`,
`f`.`FORM_NR` AS `form_nr`,
`f`.`DELIVERY_DATE` AS `delivery_date`,
`f`.`FORM_DATE` AS `form_date`,
`f`.`PAYMENT_DATE` AS `payment_date`,
MAX(`os`.`PAYED_DATE`) AS `payed_date`,
`fi`.`GROSS_MONEY` AS `gross_money`,
`fi`.`NET_PRICE` AS `net_price`,
ifnull(SUM(`os`.`PAYED_GROSS_AMOUNT`), 0) AS `payed_gross_amount`,
ifnull((`fi`.`GROSS_MONEY`
- SUM(`os`.`PAYED_GROSS_AMOUNT`)),
`fi`.`GROSS_MONEY`) AS `remaining_amount`
FROM `form` `f`
LEFT JOIN `outstanding` `os` ON `f`.`ID` = `os`.`INVOICE_ID`,
(SELECT form_id AS `FORM_ID`,
SUM(gross_money) AS `GROSS_MONEY`,
SUM(net_price) AS `NET_PRICE`
FROM form_item
GROUP BY form_id) fi
WHERE `f`.SUBTYPE <> 3
AND `fi`.FORM_ID = `f`.ID
AND `f`.STATUS = 2
AND `f`.DIRECTION = 1
AND `os`.DELETED <> 'deleted'
AND (`f`.PAYMENT_TYPE = 2 OR `f`.PAYMENT_TYPE = 4)
AND `f`.FORM_TYPE = 'Invoice'
AND `f`.deleted <> 'deleted'
GROUP BY `f`.`ID`,
`fi`.`form_id`
ORDER BY `f`.`FORM_DATE` DESC;
我也尝试了LEFT OUTER JOIN,但是没有运气:(
谢谢!
编辑:
查询尽可能简化(最后可以忽略WHERE子句)
预期结果:
表单表:
ID FORM_NR ...
1 2019/1
2 2019/2
3 2019/4
4 2019/7
...
杰出表:
INVOICE_ID PAYED_DATE PAYED_GROSS_AMOUNT ...
2 2019-02-05 100
3 2019-02-06 200
...
结果:
FORM_NR FORM_DATE ... PAYED_DATE PAYED_GROSS_AMOUNT
2019/1 2019-02-01 null 0
2019/2 2019-02-02 2019-02-05 100
2019/4 2019-02-03 2019-02-06 200
2019/7 2019-02-04 null 0
...
PAYED_GROSS_AMOUNT是因为IFNULL方法0而不是NULL。
答案 0 :(得分:0)
使用NOT EXISTS
。像这样:
select . . .
from form f
where <conditions on form> and
not exists (select 1
from outstanding o
where o.form_item = f.id and
<conditions on outstanding>
);