MYSQL GROUP BY和ORDER BY NOT TINGETHER

时间:2015-07-01 09:05:37

标签: mysql

我在google中搜索过,甚至在stactoverflow中也进行过搜索,但根据我的情况,我无法达到我需要的答案。所以我提出了我的问题。我会尝试用两个案例解释我的问题

CASE ONE:当我在查询中仅使用ORDER BY子句时:参见第1张图片。

I have commented the GROUP By clause in this image, output is just below the query

案例二:当我使用GROUP BY和ORDER BY claluse时:见第二张图片

enter image description here

我的要求是每个酒店只有单一记录没有重复,而第二个订单应该是最低的酒店价格应该在TOP;

我的意思是记录我需要记录,将third_party_rate拉为1041

您可以以文本格式查看MySql代码,如下所示:

SELECT h.hotel_id AS id,h.hotel_city AS city,h.hotel_name AS hotelname,h.hotel_star AS hotelcat,hwd.double_spl_rate, hwd.extra_bed_spl_rate,hwd.meal_plan_spl,hwd.third_party_rate,hwd.third_party_extra_bed, hwd.third_party_meal_plan,hwd.room_category,hrd.hotel_rate_from,hrd.hotel_rate_to FROM hotels_list AS h 
INNER JOIN hotel_rate_detail AS hrd ON h.hotel_id = hrd.hotels_id 
INNER JOIN hotel_week_days AS hwd ON hrd.hotel_id = hwd.h_id 
WHERE ( ('2015-07-02' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to) OR ('2015-07-03' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to) ) AND (h.hotel_city = '1')
AND (hwd.double_spl_rate != 0 OR hwd.third_party_rate != 0) AND (h.hotel_star <= '2') 
AND h.hotel_id = 364
GROUP BY h.hotel_id ORDER BY hwd.double_spl_rate,hwd.third_party_rate ASC;

注意:我在上面的上下文中只使用了id = 364只是为了显示结果,但是还有许多其他重复的酒店ID,有这种情况,所以我需要一个通用查询,它不仅适用于id = 364,还适用于其他ids以及我通过一个查询得到完整的结果

2 个答案:

答案 0 :(得分:1)

MySQL将允许这些愚蠢的查询,其中假设GROUP BY包含所有列,即使您没有指定它们。首先进行分组,因此如果只有一个结果,则排序不会做任何事情。

您需要使用MIN(third_party_rate)来获取该列的最低值。

答案 1 :(得分:1)

嘿在SQL分组完成后,您的订购就完成了。

所以在这种情况下,你可以先order你的记录。将结果与您的特定列分组,它将返回给定记录,无论您想要什么。你可以用你的查询。替换您的查询,如下所示:

e.g

select * from 
  (select * from table_name order by column_name Asc) 
  as t group by t.column_name_for_group

您的查询为。我认为这可以帮助您实现记录:

Select * from (SELECT h.hotel_id AS id,h.hotel_city AS city,h.hotel_name AS hotelname,h.hotel_star AS hotelcat,hwd.double_spl_rate, hwd.extra_bed_spl_rate,hwd.meal_plan_spl,hwd.third_party_rate,hwd.third_party_extra_bed, hwd.third_party_meal_plan,hwd.room_category,hrd.hotel_rate_from,hrd.hotel_rate_to FROM hotels_list AS h 
INNER JOIN hotel_rate_detail AS hrd ON h.hotel_id = hrd.hotels_id 
INNER JOIN hotel_week_days AS hwd ON hrd.hotel_id = hwd.h_id 
WHERE ( ('2015-07-02' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to) OR ('2015-07-03' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to) ) AND (h.hotel_city = '1')
AND (hwd.double_spl_rate != 0 OR hwd.third_party_rate != 0) AND (h.hotel_star <= '2') 
AND h.hotel_id = 364
ORDER BY hwd.double_spl_rate,hwd.third_party_rate ASC) as result_table GROUP BY result_table.id;