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秒。
我尝试过不同的子查询,但都需要“无限”时间,超过几分钟;我实际上从来没有让他们完成。
答案 0 :(得分: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);
甚至这个:
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
答案 1 :(得分:1)
以下是一个示例,您可以see it采取行动:
<强>查询强>
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
<强>结果强>
| ID | INIT | JOB | -------------------- | 1 | aa | job1 | | 2 | aa | job2 | | 4 | cc | job3 | | 5 | cc | job5 |