需要从表A中取得所有字段b相同的数据
如下,该SQL用于查询出数据库中某表的所有重复记录!
比如表A
——————————————————————
ID USER PASS
——————————————————————
1 test1 a
2 test2 b
3 test3 c
4 test3 cc
5 test3 ccc
6 test4 d
7 test5 d
8 test5 e
——————————————————————
用什么方法找出其中USER重复的数据,即
3 test3 c
4 test3 cc
5 test3 ccc
7 test5 d
8 test5 e
这只是一个例子,如果表中的数据有几百万条,如何提高查询的效率
SQL语句写了很多种了,但速度都很慢。
例如如下SQL,在表中数据量很少时执行速度还是很快的,但是当数据量打到50W时,我至今没有等到它的返回结果....
select id,user,pass
from A
where user in (
select user
from A
group by user having count(user)>1);
再ORACLE的环境下
可以考虑用EXISTS条件语句代替IN语句
Sql代码
1.SELECT A1.ID, A1.USER, A1.PASS
2.FROM A A1
3.WHERE EXISTS
4.(
5. SELECT 1
6. FROM A A2
7. WHERE A1.USER = A2.USER
8. AND A1.ID <> A2.ID
9.)
SELECT A1.ID, A1.USER, A1.PASS
FROM A A1
WHERE EXISTS
(
SELECT 1
FROM A A2
WHERE A1.USER = A2.USER
AND A1.ID <> A2.ID
)
如果是BATCH或者SP,可以考虑作一个如下的中间表B
Sql代码
1.CREATE TABLE B
2.AS
3.SELECT
4. USER, COUNT(*) AS USER_COUNT
5.FROM A
6.GROUP BY USER
7.HAVING COUNT(*) > 1
8./
9.ALTER TABLE B
10. ADD PRIMARY KEY (USER)
11./
CREATE TABLE B
AS
SELECT
USER, COUNT(*) AS USER_COUNT
FROM A
GROUP BY USER
HAVING COUNT(*) > 1
/
ALTER TABLE B
ADD PRIMARY KEY (USER)
/
然后用以下SQL进行检索
Sql代码
1.SELECT A.*
2.FROM A
3.INNER JOIN B ON
4.A.USER = B.USER
这条执行的效率怎样?
Sql代码
1.select user
2. from A
3. group by user having count(user)>1
select user
from A
group by user having count(user)>1
还有重复的几率有多大,如果超过一半的话,优化死也优化不到哪里去
可以用left join试试(mysql测试通过)
Sql代码
1.select a.id,a.user,a.pass
2.from
3. (select user
4. from A
5. group by user having count(user)>1
6. ) AS B left join A on B.user=A.user