简体   繁体   中英

MySQL query to analyze results and tag them

I have two mysql tables: invoices and payments. I would like to list all invoicerows for a certain period AND a note on if it is paid or not..

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

RESULTING:

1252515  122,50 PAID
1252514  150,40 PAID
1257425 1180,40 NOT PAID

and so on... Does not work. Can this be done in a (mysql) query?

You can use JOIN with 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

Another way you can also use 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

Try using CASE instead of IF.:

CASE WHEN EXISTS (Select * from payments WHERE payments.i_id = invoices.i_id) THEN 'PAID' ELSE 'NOT PAID' END

Simple example (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM