我想获得一组记录,其中只有日期(YYYY-MM-DD)和用户名对在多个记录中匹配,所有其他字段可以不同。
SELECT *, count(*) from table
GROUP BY username
HAVING count(username)>1 AND count(date)>1;
似乎是严重错误,我不知道如何让它发挥作用。 我在这里看到的大部分帮助都是关于匹配的整行,我只关心这两列匹配的记录。我想标记这些重复项。
我无法控制这个数据库,所以我不能接受将来的维护建议。
答案 0 :(得分:4)
create table table1
(
id int auto_increment primary key,
username varchar(30) not null,
`date` date not null
);
insert table1 (username,`date`) values ('john','2015-01-01');
insert table1 (username,`date`) values ('kim','2015-01-01');
insert table1 (username,`date`) values ('john','2015-01-01');
insert table1 (username,`date`) values ('john','2015-02-01');
insert table1 (username,`date`) values ('john','2015-03-01');
SELECT t1.*
from table1 t1
join
(
select username,`date`,count(*)
from table1
group by username,`date`
having count(username)>1
) inr
on inr.username=t1.username and inr.`date`=t1.`date`
会产生2行
+----+----------+------------+
| id | username | date |
+----+----------+------------+
| 1 | john | 2015-01-01 |
| 3 | john | 2015-01-01 |
+----+----------+------------+
2 rows in set (0.03 sec)
根据OP请求,有一个标记dupe的列供以后工作,而不是select语句。请注意,您可以Alter Table
添加此可以为空的标记列,设置它,在闲暇时使用值,稍后Alter Table
并删除它。
但是我将从这里开始使用带有新标志列的create table:
create table table1
(
id int auto_increment primary key,
username varchar(30) not null,
`date` date not null,
dupeflag int null -- <---- New flag column, nullable, ignored on inserts below
);
insert table1 (username,`date`) values ('john','2015-01-01');
insert table1 (username,`date`) values ('kim','2015-01-01');
insert table1 (username,`date`) values ('john','2015-01-01');
insert table1 (username,`date`) values ('john','2015-02-01');
insert table1 (username,`date`) values ('john','2015-03-01');
update table1 t1
join
( select username,`date`,count(*)
from table1
group by username,`date`
having count(username)>1
) inr
on inr.username=t1.username and inr.`date`=t1.`date`
set dupeflag=1;
-- 2 rows affected
select * from table1;
+----+----------+------------+----------+
| id | username | date | dupeflag |
+----+----------+------------+----------+
| 1 | john | 2015-01-01 | 1 |
| 2 | kim | 2015-01-01 | NULL |
| 3 | john | 2015-01-01 | 1 |
| 4 | john | 2015-02-01 | NULL |
| 5 | john | 2015-03-01 | NULL |
+----+----------+------------+----------+
5 rows in set (0.00 sec)