gpt4 book ai didi

MYSQL GROUP BY 和 ORDER BY 没有按预期一起工作

转载 作者:行者123 更新时间:2023-11-29 05:17:13 26 4
gpt4 key购买 nike

我将尝试用两个案例来解释我的问题:

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

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

  2. 当我同时使用 GROUP BY 和 ORDER BY 子句时:参见第二张图片

    enter image description here

我的要求是每家酒店只获取一条记录,不能重复,第二个ordered by应该是最低的酒店价格应该在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 但对于其他 ID 也是如此,这样我就可以通过一次查询获得完整的结果。

最佳答案

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

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

关于MYSQL GROUP BY 和 ORDER BY 没有按预期一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com