是否可以将此查询转换为使用连接而不是子查询?

时间:2009-04-09 14:27:39

标签: sql mysql join subquery

SELECT
    number, count(id)
FROM
    tracking
WHERE
    id IN (SELECT max(id) FROM tracking WHERE splitnr = 'a11' AND number >0 AND timestamp >= '2009-04-08 00:00:00' AND timestamp <= '2009-04-08 12:55:57' GROUP BY ident)
GROUP BY
    number

3 个答案:

答案 0 :(得分:1)

这个怎么样:

SELECT    number, count(id)
FROM    tracking 
  INNER JOIN (SELECT max(id) ID FROM tracking  
                 WHERE splitnr = 'a11' AND 
                       number >0 AND timestamp >= '2009-04-08 00:00:00' AND 
                       timestamp <= '2009-04-08 12:55:57'
              GROUP BY ident
             ) MID ON (MID.ID=tracking.id)
WHERE   
GROUP BY number

答案 1 :(得分:0)

稍微有点难以确保在没有看到数据并且确切地知道你想要实现的目标的情况下完全正确地完成了它但是我亲自将子查询转换为视图然后加入其中,所以:

create view vMaximumIDbyIdent

as

SELECT ident, max(id) maxid

FROM tracking 

WHERE splitnr = 'a11' AND number >0 

AND timestamp >= '2009-04-08 00:00:00' 

AND timestamp <= '2009-04-08 12:55:57' 

GROUP BY ident

then:


SELECT

    number, count(id)
FROM

    tracking,

    vMaximumIDbyIdent

WHERE

    tracking.id = vMaximumIDbyIdent.maxid

GROUP BY

    number

更具可读性和可维护性。

答案 2 :(得分:0)

你能不能这样做:

SELECT
    number,
    count(id)
FROM
    tracking
WHERE
    splitnr = 'a11' AND number > 0 AND timestamp >= '2009-04-08 00:00:00' AND timestamp <= '2009-04-08 12:55:57'
GROUP BY
    number
ORDER BY
    number DESC
LIMIT 0,1

(顺便说一下我真的不懂MySQL)

我假设这会给你回相同的结果集,你按照desc号码订购,因为你想要最大的一个,对吗?然后你可以把WHERE子句放入并将它限制为1给你第一个与MAX基本相同的(我认为)这样就完全删除了JOIN。

编辑:我认为你不需要GROUP BY识别