具有最高COUNT的MySQL GROUP BY字段(基于JOIN)

时间:2015-04-10 12:45:21

标签: mysql sql innodb

SELECT COUNT(dev_link.id) c, pattern.direction, pattern.section, (
    SELECT to_stop AS `stop`
    FROM dev_link d
    WHERE d.section = section
    ORDER BY d.sequence DESC
    LIMIT 1
) code
FROM pattern
INNER JOIN dev_link ON dev_link.section = pattern.section
WHERE pattern.service = "YSEO252"
GROUP BY pattern.code
ORDER BY c DESC

enter image description here

以上是查询及其结果。目前这是选择太多数据,我需要将其缩小到以下几点:

方向outbound的1行和方向inbound的另一行。如果只是我可以轻松地GROUP BY方向。但是,我需要选择inboundoutbound行,c值最高。因此,基于上面的结果,将选择第1行和第3行。

如何更改查询以便返回这些行?

4 个答案:

答案 0 :(得分:1)

我会使用变量来模拟row_number()

SELECT * FROM (
    SELECT * , 
        @rn := if(@prevDirection = direction, @rn + 1, 1) as rn,
        @prevDirection := direction,
    FROM (
        SELECT COUNT(dev_link.id) c, pattern.direction, pattern.section, (
            SELECT to_stop AS `stop`
            FROM dev_link d
            WHERE d.section = section
            ORDER BY d.sequence DESC
            LIMIT 1
        ) code
        FROM pattern
        INNER JOIN dev_link ON dev_link.section = pattern.section
        WHERE pattern.service = "YSEO252"
        GROUP BY pattern.code
    ) t1 ORDER BY direction, c DESC
) t1 WHERE rn = 1

答案 1 :(得分:1)

( SELECT ... WHERE ... AND pattern.direction='inbound' ... LIMIT 1)
UNION ALL
( SELECT ... WHERE ... AND pattern.direction='outbound' ... LIMIT 1 );

否则,每个SELECT都与原始SELECT类似。

答案 2 :(得分:0)

你只需要使用MAX函数和group by子句,如:

SELECT MAX(c)
FROM mytable
GROUP BY direction

答案 3 :(得分:-2)

您必须使用having子句。

SELECT COUNT(dev_link.id) c, pattern.direction, pattern.section, (
    SELECT to_stop AS `stop`
    FROM dev_link d
    WHERE d.section = section
    ORDER BY d.sequence DESC
    LIMIT 1
) code
FROM pattern
INNER JOIN dev_link ON dev_link.section = pattern.section
WHERE pattern.service = "YSEO252"
GROUP BY pattern.code
HAVING COUNT(dev_link.id) = MAX(COUNT(dev_link.id))
ORDER BY c DESC