写一个没有组子查询的查询?

时间:2012-11-18 11:07:32

标签: mysql

根据我的理解,每次查看一行时都会调用子查询,在这种情况下,每行都会被查看。

如何重写此查询?子查询只需要运行一次但我不能想到如何在我必须删除组中只有1个条目的id时选择id(我希望组计数> 1)。

目的是获取与其他行具有相同大小的行列表

select id 
from file 
where size in 
    ( 
    select size from 
        (
        select count(*) as c, size 
        from file 
        group by size 
        having c>1 and size>0
        ) as t
    )

3 个答案:

答案 0 :(得分:1)

恕我直言,优化器应该处理它,所以你不必这样做。

让MySQL解释声明。

除此之外,您还可以将子查询存储在临时表中

更新

CREATE TEMPORARY TABLE tmpTab
  SELECT count(*) AS c, size 
  FROM file 
  GROUP BY size 
  HAVING c>1 AND size>0;

SELECT id 
FROM file 
WHERE size IN 
    ( SELECT size FROM tmpTab )

答案 1 :(得分:1)

您只能使用子查询而不是两个:

select id 
from file 
where size in (
    select size 
    from file 
    group by size 
    having count(*)>1 and size>0
    )

但是如果你想只使用连接,你可以使用这样的东西:

select distinct file.id
from file inner join file file1 on file.size = file1.size
where file.size>0 and file.id <> file1.id

答案 2 :(得分:1)

加入子查询怎么样?

SELECT  a.*
FROM    `FILE` a 
        INNER JOIN
        (
            SELECT  COUNT(*) as c, `SIZE` 
            FROM    `file `
            WHERE   `size` > 0
            GROUP BY size 
            having  COUNT(*) > 1
        ) b ON a.Size = b.Size