通过多个提醒(一对多关系)获取唯一发票?
fetch unique invoices though several reminders (one-to-many relation)?
这是一个简化的 sqlfiddle 作为我的问题的基础:
http://sqlfiddle.com/#!15/c114a/7
第一张发票有两个从其他两个日期发送的提醒:
我想获取所有应提醒的发票 - 一次。现在它通过提醒重复。
我只想要最后的提醒
SELECT inv_id, inv_due, rem_type
FROM inv
LEFT JOIN remrec ON remrec_inv = inv_id
LEFT JOIN rem ON rem_id = remrec_rem
WHERE inv_due < '2015-01-02'
而且我知道我可以使用 greast(inv_due,rem1,rem2,rem3):
比较并从发票和所有提醒中获取最新日期
SELECT inv_id,rem_type,greatest(inv_due,
(CASE WHEN rem_date<'2015-01-02' AND rem_type='1' THEN rem_date ELSE NULL END),
(CASE WHEN rem_date<'2015-01-02' AND rem_type='2' THEN rem_date ELSE NULL END),
(CASE WHEN rem_date<'2015-01-02' AND rem_type='3' THEN rem_date ELSE NULL END)) as max
FROM inv
LEFT JOIN remrec ON inv_id=remrec_inv
LEFT JOIN rem ON rem_id=remrec_id
WHERE inv_due < '2015-01-02'
因此每个提醒都可以包含多个发票。因此 rem 和 remrec.
问题是:如何只获取应提醒的唯一发票?
提前感谢您提供任何线索。
我想我找到了解决办法:
SELECT inv_id, inv_due, max(rem_type)
FROM inv
LEFT JOIN remrec ON inv_id=remrec_inv
LEFT JOIN rem ON rem_id=remrec_rem
WHERE greatest(inv_due,rem_date) < '2015-01-05'
GROUP BY inv_id, inv_due
编辑:使用多个提醒效果更好:
SELECT DISTINCT inv_id, inv_due
FROM inv
LEFT JOIN remrec ON inv_id=remrec_inv
LEFT JOIN rem ON rem_id=remrec_rem
WHERE inv_due<'2015-01-05'
GROUP BY inv_id,inv_due
HAVING greatest(max(rem_date),inv_due)<'2015-01-05'
FWIW.
这是一个简化的 sqlfiddle 作为我的问题的基础:
http://sqlfiddle.com/#!15/c114a/7
第一张发票有两个从其他两个日期发送的提醒:
我想获取所有应提醒的发票 - 一次。现在它通过提醒重复。
我只想要最后的提醒
SELECT inv_id, inv_due, rem_type
FROM inv
LEFT JOIN remrec ON remrec_inv = inv_id
LEFT JOIN rem ON rem_id = remrec_rem
WHERE inv_due < '2015-01-02'
而且我知道我可以使用 greast(inv_due,rem1,rem2,rem3):
比较并从发票和所有提醒中获取最新日期SELECT inv_id,rem_type,greatest(inv_due,
(CASE WHEN rem_date<'2015-01-02' AND rem_type='1' THEN rem_date ELSE NULL END),
(CASE WHEN rem_date<'2015-01-02' AND rem_type='2' THEN rem_date ELSE NULL END),
(CASE WHEN rem_date<'2015-01-02' AND rem_type='3' THEN rem_date ELSE NULL END)) as max
FROM inv
LEFT JOIN remrec ON inv_id=remrec_inv
LEFT JOIN rem ON rem_id=remrec_id
WHERE inv_due < '2015-01-02'
因此每个提醒都可以包含多个发票。因此 rem 和 remrec.
问题是:如何只获取应提醒的唯一发票?
提前感谢您提供任何线索。
我想我找到了解决办法:
SELECT inv_id, inv_due, max(rem_type)
FROM inv
LEFT JOIN remrec ON inv_id=remrec_inv
LEFT JOIN rem ON rem_id=remrec_rem
WHERE greatest(inv_due,rem_date) < '2015-01-05'
GROUP BY inv_id, inv_due
编辑:使用多个提醒效果更好:
SELECT DISTINCT inv_id, inv_due
FROM inv
LEFT JOIN remrec ON inv_id=remrec_inv
LEFT JOIN rem ON rem_id=remrec_rem
WHERE inv_due<'2015-01-05'
GROUP BY inv_id,inv_due
HAVING greatest(max(rem_date),inv_due)<'2015-01-05'
FWIW.