Search code examples
mysqlsqljoincoalesce

Using joint statement with ifnull function MySQL


I just want to replace the reference id with name from item table in the result as I showed in last table

1st table and Parent table

id item amount tax status
1 4 20 2 Y
2 5 15 1 N
3 6 5 0 N

2nd table and child table

id item p_id amount tax
1 1 1 10 1
2 2 2 10 1
3 3 1 15 1

3rd table

id item
1 mobile
2 heater
3 mouse
4 electronic
5 software
6 papers

What I get from this code

SELECT IFNULL(child.item, parent.item) AS item, 
       IFNULL(child.amount, parent.amount) AS amount,
       IFNULL(child.tax, parent.tax) AS tax
FROM parent
LEFT JOIN child ON parent.id = child.p_id
item amount tax
1 10 1
2 10 1
3 15 1
5 15 1
6 5 0

What I want is

item amount tax
mobile 10 1
heater 10 1
mouse 15 1
software 15 1
papers 5 0

please help me to achieve this


Solution

  • Simply join the item table using the item ID you are already showing in your query:

    SELECT
      i.item, 
      COALESCE(c.amount, p.amount) AS amount,
      COALESCE(c.tax, p.tax) AS tax
    FROM parent p
    LEFT JOIN child c ON c.p_id = p.id
    JOIN item i ON i.id = COALESCE(c.item, p.item)
    ORDER BY i.item;
    

    (I am using COALESCE instead of IFNULL, because this is standard SQL. But you can stick with IFNULL, if you like it better.)