我有两个mysql表:发票和付款。我想在一段时间内列出所有的invoicerow以及是否付款的说明..
SELECT invoices.i_id, invoices.sum, IF EXISTS (Select * from payments WHERE payments.i_id = invoices.i_id) THEN 'PAID' ELSE 'NOT PAID')
FROM invoices
WHERE invoices.date >= 2014-01-01
AND invoices.date <= 2014-01-31
所得:
1252515 122,50 PAID
1252514 150,40 PAID
1257425 1180,40 NOT PAID
依旧...... 不行。这可以在(mysql)查询中完成吗?
答案 0 :(得分:2)
您可以将JOIN
与CASE
SELECT i.i_id, i.`sum`,
(CASE WHEN p.i_id IS NOT NULL THEN 'PAID' ELSE 'NOT PAID' END) `status`
FROM invoices i
LEFT JOIN payments p ON(p.i_id = i.i_id)
WHERE i.date >= 2014-01-01
AND i.date <= 2014-01-31
另一种方法也可以使用IF
SELECT i.i_id, i.`sum`,
IF(p.i_id IS NULL, 'NOT PAID', 'PAID') `status`
FROM invoices i
LEFT JOIN payments p ON(p.i_id = i.i_id)
WHERE i.date >= 2014-01-01
AND i.date <= 2014-01-31
答案 1 :(得分:0)
尝试使用CASE而不是IF。:
CASE WHEN EXISTS (Select * from payments WHERE payments.i_id = invoices.i_id) THEN 'PAID' ELSE 'NOT PAID' END
简单示例(fiddle):
CREATE TABLE tbl1 (id INT);
CREATE TABLE tbl2 (id INT);
INSERT INTO tbl1 VALUES (1),(2);
INSERT INTO tbl2 VALUES (1);
SELECT id
,CASE WHEN EXISTS (SELECT * FROM tbl2 WHERE tbl2.id = tbl1.id) THEN 'PAID' ELSE 'NOT PAID' END
FROM tbl1