0

I have two tables.

Invoices

ID | Amount
-----------
1  | 123.54
2  | 553.46
3  | 431.34
4  | 321.31
5  | 983.12

Credit Memos

ID | invoice_ID | Amount
------------------------
1  | 3          | 25.50
2  | 95         | 65.69
3  | 51         | 42.50

I want to get a result set like this out of those two tables

ID | Amount | Cr_memo
---------------------
1  | 123.54 |
2  | 553.46 |
3  | 431.34 | 25.50
4  | 321.31 |
5  | 983.12 |

I've been messing with joins and whatnot all morning with no real luck.

Here is the last query I tried, which pulled everything from the Credit Memo table...

SELECT A.ID, A.Amount FROM Invoices AS A
LEFT JOIN Credit_Memos AS B ON A.ID = B.invoice_ID

Any help or pointers are appreciated.

2
  • 2
    Query looks fine add B.Cr_memo in select Commented Nov 22, 2014 at 17:04
  • Your query works (if you add the column from the second table): sqlfiddle.com/#!6/b2a53/2/0 Commented Nov 22, 2014 at 17:07

3 Answers 3

2

Your query would work fine. Just add Credit_memo.Amount with an alias:

SELECT Inv.ID,Inv.Amount,IFNULL(C.Amount,'') AS Cr_memo
FROM Invoices Inv LEFT JOIN
    Credit_Memos C ON Inv.ID=C.invoice_ID

Result:

ID  AMOUNT  CR_MEMO
1   124 
2   553 
3   431     25.50
4   321 
5   983 

See result in SQL FIDDLE.

Sign up to request clarification or add additional context in comments.

1 Comment

Ha, thank you. That worked perfect. I totally forgot about IFNULL.
0

You almost got the answer Left Outer Join is what you need but you missed to select Cr_memo from Credit_Memos table. Since you don't want to show Null values when there is no Invoices_ID in Credit Memos table use IFNULL to make NULL's as Empty string

SELECT A.ID, A.Amount, IFNULL(B.Cr_memo,'') AS Cr_memo
FROM Invoices AS A
LEFT JOIN Credit_Memos AS B 
ON A.ID = B.invoice_ID

Comments

0

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.

  SELECT A.ID, A.Amount, IFNULL(B.amount,0) AS Cr_memo  FROM Invoices AS A
  LEFT JOIN Credit_Memos AS B ON A.ID = B.invoice_ID

here is some useful link about left join link and another

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.