0
Table kal
id integer primary key
init char 4 indexed
job char4

id  init job
--+----+------
1 | aa | job1
2 | aa | job2
3 | bb | job1
4 | cc | job3   
5 | cc | job5

我想显示 init 超过一行的所有行:

id  init job
--+----+------
1 | aa | job1
2 | aa | job2
4 | cc | job3   
5 | cc | job5

我试过了:

select * from kal where init in (select init from kal group by init having 
count(init)>2);

实际上,该表有 60000 行,查询是

count(init)<40, 

但这需要大量时间,phpmyadmin 和我的耐心都用完了。

两个都

select init from kal group by init having count(init)>2)

select * from kal where init in ('aa','bb','cc')

“无时间”运行,不到 0.02 秒。

我尝试了不同的子查询,但都需要“无限”时间,超过几分钟;我实际上从来没有让他们完成。

4

2 回答 2

2

你试过了EXISTS吗?

select *
from yourtable t1
where exists (select count(*)
              from yourtable t2
              where t1.init = t2.init
              group by t2.init
              having count(*) >= 2);

SQL Fiddle with Demo

甚至这样:

select *
from yourtable t1
left join
(
  select count(*) cnt, init
  from yourtable
  group by init
) t2
  on t1.init = t2.init
where t2.cnt > 1

SQL Fiddle with Demo

于 2012-09-17T21:31:02.963 回答
1

这是一个示例,您可以看到它的实际效果:

询问

SELECT a.id, a.init, a.job
FROM kal a
INNER JOIN
  (SELECT init, COUNT(init) 
  FROM kal
  GROUP BY init
  HAVING COUNT(init) > 1) b ON b.init = a.init

结果

| 身份证 | 初始化 | 工作 |
--------------------
| 1 | 啊 | 工作1 |
| 2 | 啊 | 工作2 |
| 4 | 抄送| 工作3 |
| 5 | 抄送| 工作5 |
于 2012-09-17T21:28:34.147 回答