GROUP BY查询忽略ORDER BY子句

时间:2011-02-23 03:27:46

标签: mysql sql

SELECT
    deal_woot.*,
    site.woot_off,
    site.name AS site_name
FROM deal_woot
INNER JOIN site ON site.id = site_id
WHERE site_id IN (2, 3, 4, 5, 6)
GROUP BY site_id
ORDER BY deal_woot.id DESC
LIMIT 5

我想在分组之前先订购,我该如何做到这一点?

4 个答案:

答案 0 :(得分:1)

使用以下子查询:SELECT *,COUNT(*) FROM (SELECT * from actions order by date DESC) AS actions GROUP BY ip;

答案 1 :(得分:0)

由于您按site_id进行分组,因此只会返回1 deal_woot行。请尝试按MAX()排序,这将为每id返回最高site_id

SELECT
    deal_woot.*,
    site.woot_off,
    site.name AS site_name
FROM deal_woot
INNER JOIN site ON site.id = site_id
WHERE site_id IN (2, 3, 4, 5, 6)
GROUP BY site_id
ORDER BY MAX(deal_woot.id) DESC
LIMIT 5

注意:由于它是UB,实际上会返回deal_woot行,请尝试查询您的查询:

SELECT
    deal_woot.*,
    site.woot_off,
    site.name AS site_name
FROM site JOIN (
    SELECT site_id, MAX(deal_woot.id) MaxID
    FROM deal_woot
    WHERE site_id IN (2, 3, 4, 5, 6)
    GROUP BY site_id
  ) sg ON site.id = sg.site_id
  JOIN deal_woot
    ON site.id = deal_woot.site_id AND deal_woot.id = sg.MaxID
ORDER BY sg.MaxID DESC
LIMIT 5

答案 2 :(得分:0)

您正在site_id上​​执行GROUP BY,而您正在使用deal_woot.id安排记录。

即使你在Group之前进行Order By,输出也会保持不变。

您是否有任何具体要求来做这些事情,因为您所怀疑的与Order by和group by无关。

答案 3 :(得分:-1)

SELECT
     deal_woot.*,
     site.woot_off,
     site.name AS site_name 
FROM deal_woot 
INNER JOIN site ON site.id = site_id 
WHERE site_id IN (2, 3, 4, 5, 6) 
GROUP BY deal_woot.id DESC, site_id 
LIMIT 5

我认为deal_woot.id是唯一的,分组将基于site_id