Question

I have a MySQL database containing the following:

Products

id | name              | indexname   |units
--------------------------------------------
1  |Mydełko Fa         |FA_INDEX     |szt.
2  |Ręcznik elegancki  |RECZNIK_ELEG |szt.
3  |Płyn do czyszczenia|CZYS_PLYN    |l

Prices

id | user_id | product_id | price
-----------------------------------
2  |NULL     |1           |21.32
3  |3        |1           |20
4  |NULL     |2           |43.21
5  |NULL     |3           |12.12

So as you can see there are 2 prices for product of id 1. I want to prepare a query that will return

id | name              | indexname   |units |price
---------------------------------------------------
1  |Mydełko Fa         |FA_INDEX     |szt.  |20
2  |Ręcznik elegancki  |RECZNIK_ELEG |szt.  |43.21
3  |Płyn do czyszczenia|CZYS_PLYN    |l     |12.12

So what I want is to get all rows where user_id is 3 or if such row not exists then the one where user_id is null.

I tried

SELECT * 
FROM `products` p1 
JOIN `prices` p2 ON p1.id = p2.product_id 
WHERE `user_id` = 3 OR `user_id` is null

and some others however with no success... Could you help?

Was it helpful?

Solution

A simple way would be to get both at once, of course you'll get a null value if no user price exists for that user:

SELECT p1.*, p2.price AS null_price, p3.price AS user_price
FROM `products` p1 
JOIN `prices` p2 ON p1.id = p2.product_id AND `p2.user_id` IS NULL
LEFT JOIN `prices` p3 ON p1.id = p3.product_id AND `p3.user_id` = 3

Then use whatever programming language you are using to determine if the field is null, and which price to use.

OTHER TIPS

I think what you need is this:

SELECT * FROM products p1
LEFT JOIN prices p2 ON p1.id = p2.product_id
WHERE user_id IS NOT NULL OR p2.product_id IN (
  SELECT product_id FROM prices GROUP BY product_id HAVING COUNT(*) = 1)

Try this: http://sqlfiddle.com/#!2/bfd50/1/0

SELECT * 
FROM products p
JOIN prices pr ON pr.product_id = p.id
WHERE pr.user_id = 3 OR pr.user_id IS NULL;

Without giving the error you're receiving, it's a little hard to provide a concrete answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top