sql查询按两个字段查询重复记录

我想查询表shiyan003,按xm,sfzhm这两个字段查
select * from shiyan003 a
where (a.xm,a.sfzhm) in (select xm,sfzhm from shiyan003 group by xm,sfzhm having count(*) > 1)
提示:第2行 ',' 附近有语法错误。怎么改呢

用关键字 stinct,select stinct 字段,是不重复的意思。代码的实例如下:

查询order_id和loan_lind两个字段相同的记录:

select distinct a.order_preview_id, a.order_id, a.loan_kind

from ddk_order_preview_info a

join ddk_order_preview_info b

on a.order_preview_id != b.order_preview_id

where a.order_id = b.order_id and a.loan_kind = b.loan_kind;

扩展资料

SQL数据库查询出一张表中重复的数据,按某个字段来查找的实例:

例如表名为Course:

需要查询出name的重复,解答如下:

补充:

如:查询每个姓名出现大于2次,SQL如下

SELECT COUNT(NAME) as '出现次数',  NAME FROM  表名

GROUP BY  NAME   HAVING count(NAME) > 2   ORDER BY  出现次数   DESC 

参考资料来源:MySql官方网站-MySQL 8.0参考手册-13.2.10 SELECT语法

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-12-15

1、改成如下语句:

select shiyan003.* from shiyan003 right join

(select xm,sfzhm from shiyan003 group by xm,sfzhm having count(*) > 1) a

on a.xm = shiyan003.xm and a.sfzhm = shiyan003.sfzhm

2、测试数据如下:

3、测试结果如下:

4、分析题中语句:

以一个字段为基准查询重复记录,题中的SQL语句是一种常见的解决方法。
现在以两个字段为基准查重,题中的语句就无能为力了,需做变通。

以下是题中核心语句的执行结果

已经查出表中的重复记录了,只是缺少shiyan003表的其它字段。
我们以它为基准,联接shiyan003表,即可得最终结果。

5、运用Right join 右连接

right join是以a表的记录为基础的,shiyan003可以看成左表,a可以看成右表,right join是以右表为准的。换句话说,右表a的记录将会全部表示出来,而左表(shiyan003)只会显示符合搜索条件的记录(例子中为: a.xm = shiyan003.xm and a.)。A表记录不足的地方均为NULL。

图中标灰的是左表,标黄的是右表。
注:如果语句都写在一行上,左表右表就很容易分辨。

参考资料:

百度百科-right join

本回答被网友采纳
第2个回答  2013-09-12

应该是in关键字不支持多字段吧,你这样试一下

select *
  from shiyan003 a
 where exists (select 1
          from (select xm, sfzhm
                  from shiyan003
                 group by xm, sfzhm
                having count(*) > 1) s
         where s.xm = a.xm
           and s.sfzhm = a.sfzhm)

第3个回答  2013-09-12
select *
from shiyan003 a
where exists (select 1
from (select xm, sfzhm
from shiyan003
group by xm, sfzhm
having count(*) > 1) s
where s.xm = a.xm
and s.sfzhm = a.sfzhm)本回答被提问者采纳
第4个回答  2013-09-12
select * from shiyan003 a
where a.xm in (select xm from shiyan003 group by xm,sfzhm having count(*) > 1)
and a.sfzhm in (select sfzhm from shiyan003 group by xm,sfzhm having count(*) > 1)
原句的错在in的使用上本回答被网友采纳