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
以上是查询及其结果。目前这是选择太多数据,我需要将其缩小到以下几点:
方向outbound
的1行和方向inbound
的另一行。如果只是我可以轻松地GROUP BY
方向。但是,我需要选择inbound
和outbound
行,c
值最高。因此,基于上面的结果,将选择第1行和第3行。
如何更改查询以便返回这些行?
答案 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