George George - 5 months ago 7
MySQL Question

Mysql select all rows from table1 and matching rows from table2 or return null

I need to get all products columns plus the column unit_price from price_list where all the conditions match.

The problem is my select statement gets only the first 2 products, id: 1, 2, I need to get product with id 3,4 and so on, but with unit_price null because there is no match in price_list for that quantity.

products
--------------------------------------------
id product_code purchase_type quantity
1 106 new 5
2 107 renew 26
3 107 renew 101
4 107 renew 150


price_list
----------------------------------------------------------------------
id product_code purchase_type minimum maximum unit_price
1 106 new 1 25 20
2 106 new 26 50 16
3 106 new 51 100 14



SELECT
`products`.`id` AS `product_id`,
`products`.`product_code` AS `product_product_code`,
`products`.`purchase_type` AS `product_purchase_type`,
`products`.`update_type` AS `product_update_type`,
`products`.`quantity` AS `product_quantity`,
`price_list`.`product_code` AS `price_list_product_code`,
`price_list`.`purchase_type` AS `price_list_purchase_type`,
`price_list`.`update_type` AS `price_list_update_type`,
`price_list`.`minimum` AS `price_list_minimum`,
`price_list`.`maximum` AS `price_list_maximum`,
`price_list`.`unit_price` AS `price_list_unit_price`
FROM
`products`
INNER JOIN `price_list` ON `products`.`product_code` = `price_list`.`product_code`
WHERE
`products`.`product_code` = price_list.product_code
AND `products`.`purchase_type` = price_list.purchase_type
AND `products`.`update_type` = price_list.update_type
AND `products`.`quantity` >= price_list.minimum
AND `products`.`quantity` <= price_list.maximum
ORDER BY
`products`.`id` ASC


I would like my select statement to get me something like this:

Select Result:
-------------------------------------------------------
id product_code purchase_type quantity unit_price
1 106 new 5 20
2 107 renew 26 16
3 107 renew 101 null
4 107 renew 150 null


Current select gets only id 1 and 2.

Answer

Your possible solution is

    SELECT
    `products`.`id` AS `product_id`,
    `products`.`product_code` AS `product_product_code`,
    `products`.`purchase_type` AS `product_purchase_type`,
    `products`.`quantity` AS `product_quantity`,
    `price_list`.`product_code` AS `price_list_product_code`,
    `price_list`.`purchase_type` AS `price_list_purchase_type`,
    `price_list`.`minimum` AS `price_list_minimum`,
    `price_list`.`maximum` AS `price_list_maximum`,
    `price_list`.`unit_price` AS `price_list_unit_price`
FROM
    `products`
LEFT JOIN `price_list` ON `products`.`product_code` = `price_list`.`product_code`
AND `products`.`purchase_type` = price_list.purchase_type
AND `products`.`quantity` >= price_list.minimum
AND `products`.`quantity` <= price_list.maximum
ORDER BY
    `products`.`id` ASC

It will be better if you have more data with sqlfiddle link.

Comments