Mike
Mike

Reputation: 5788

MySQL cheapest price query

So what i need is to get the cheapest price for an object. There can be n prices and prices can be week prices or day prices. I need the cheapest price no matter if it's a day or a week price. I tried that with the below query. But i get also some NULL rows. Secondly if a day price is the cheapest, then i need that single day price and not a multiple of seven, like my query below does it.

So the below data should get me this when searching for the two objects:

id | oid | price | type (day or week)
-------------------------------------
 2 |  1  | 65    | w
 3 |  2  | 9     | d

I hope it's understandable. Thanks for any help!


Objects Table:

id | title
-----------
 1 | Object 1
 2 | Object 2 

Prices Table:

| oid | price | type (day or week)
----------------------------------
|  1  | 10    | d
|  1  | 65    | w
|  2  | 9     | d
|  2  | 70    | w

My query:

SELECT o.id, p.oid, p.price, p.type
FROM objects AS o    
LEFT JOIN prices AS c ON p.oid= o.id
AND p.price = 
(
SELECT MIN(IF(type="w",price, price*7)) FROM prices
WHERE oid= o.id
)  
LEFT JOIN ...
LEFT JOIN ...
WHERE ...
GROUP BY o.id ORDER BY p.price ASC

Upvotes: 1

Views: 194

Answers (3)

Seabath
Seabath

Reputation: 36

To avoid NULL rows, you should use inner join instead of left join.

For your 2nd part, I didn't well understood what you want to do.

edit: try this query:

select p.id, o.id, p.price, p.type
  from price as p
  inner join object as o
    on p.id_object = o.id
  where if (p.type = "w", price, price * 7) <= (
   select min(if(p.type = "w", price, price *7))
   from price
   where id_object = o.id 
  )
  order by p.price asc;

Upvotes: 1

Roy D&#39;atze
Roy D&#39;atze

Reputation: 156

Edited answer:

SELECT o.id, p.price, p.type
FROM objects AS o    
LEFT JOIN  prices p ON p.oid= o.id
AND IF(p.type="w",p.price, p.price*7) <= 
(
SELECT MIN(IF(p2.type="w",p2.price, p2.price*7)) FROM prices p2
WHERE p2.oid= o.id
)  
....

Upvotes: 0

Jimi WIlls
Jimi WIlls

Reputation: 348

add

AND price IS NOT NULL

to your A WHERE clause in the first SELECT, will get rid of null values.

Upvotes: 0

Related Questions