My first table is an item table. (invoice_inventory)
My second table is the pricelist (inventory_prices), there I have a default price list (company_id = 0) and several special price lists (but not for every company).
With the following query I try to get all items with their prices for the company_id = 2.
It should use the special price list (company_id = 2 if it exists) else it should use the default price (company_id = 0).
I thought by GROUPING + ORDERING it would work, but I forgot that GROUP BY gets executed before ORDER.
I think I may need a subquery, but I am not sure.
SELECT invoice_inventory.*, invoice_inventory_prices.*
FROM invoice_inventory
LEFT JOIN invoice_inventory_prices
ON `invoice_inventory`.`inventory_id`
= `invoice_inventory_prices`.`inventory_id`
WHERE (company_id = 2 OR company_id = 0)
GROUP BY invoice_inventory.inventory_id
ORDER BY company_id DESC
I am going to use two
LEFT JOINs the first will go get the Default pricesdp aliasand the second will get the Special prices (company_id=2)sp aliasThe
CASEis used to determine if a Special price exists, use it, otherwise use the default.You did not give a column list, so I took a guess at the name of the price column. If you require a second (or more) column, you can add additional
CASEstatements.