简体   繁体   English

MySQL最便宜的价格查询

[英]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. 可以有n个价格,价格可以是周价格或日价格。 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. 其次,如果一天的价格最便宜,那么我需要的是这一天的价格,而不是7的倍数,就像下面的查询一样。

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

To avoid NULL rows, you should use inner join instead of left join. 为避免NULL行,应使用内部联接而不是左联接。

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;

add

AND price IS NOT NULL

to your A WHERE clause in the first SELECT, will get rid of null values. 到第一个SELECT中的A WHERE子句,将摆脱空值。

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
)  
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM