Tuesday, 28 August 2018

The left join of Mysql fails to return all values ​​from the first table

I've two tables named table1 and table2. table2 may have elements from table1. I'd like to show all the results from table2 with the price if available in table1 and with status 1. If no product matches in table1 and also status is 0, need to return price as 0.

table1
id  pname       item_code   price   status

1   product1    abcd        200       1
2   product2    pqrs        500       1
3   product3    wxyz        425       1
4   product5    mnop        100       0

and table2 as follows
id  item_code   

10  efgh
11  abcd
12  pqrs
13  mnop

I have tried following query
SELECT `t2`.`id`, `t2`.`item_code`, `t1`.`price`,`t1`.`pname`, COUNT(t2.item_code) AS sellers FROM (`table2` as t2) LEFT JOIN `table1` as t1 ON `t1`.`item_code` = `t2`.`item_code` WHERE `t1`.`status` = 1 GROUP BY `t2`.`item_code`

but it returns common values in table1 and table2 with status 1, but I need all records from table2 with price as 0 if nothing match in table1 or status 0 in table1.
Expected output
id  item_code   price

10  efgh        0
11  abcd        200
12  pqrs        500
13  mnop        0

Any help please.
Thanks,

Not sure about your current query which is having count and group by however you can do as below
select
t2.id,
t2.item_code,
case
  when t1.status = 1 then t1.price
  else 0
end as price
from table2 t2
left join table1 t1 on t1.item_code = t2.item_code

Now note that if table1 has multiple matching values from table2 in that case we may need grouping data.

0 comments:

Post a Comment