MYSQL之进阶实战笔试题(四)
现有一表user_login_table代表表名
user_name代表用户ID
date代表用户登录时间
其结构数据如下:
例题5.删除重复值user_name并保留重复值中最小的date
思路:建立储存重复数据的临时表,通过exists查询删掉其他数据保留最小日期
具体步骤和代码如下:
第一步,建立临时表
create temporary table table2 (user_name int not null, date_min date not null);
第二步,在临时表中插入重复且date最小的数据
insert into table2
(user_name,date_min)
select user_name,
min(date)
from table1
group by user_name
having count(1)>=2;
第三步,删除在临时表中的ID但保留date最小的行
delete from table1
where exists
(select *
from table2
where table2.user_name=table1.user_name
and date(table1.date)!=table2.date_min);
例题6:查找表table 中列a或列b中重复的数据
思路一:单独查找某一列重复值通过union做连接
具体代码如下:
select a ,"a列重复值" as aa from table group by a having count(1)>2
union
select b,"b列重复值" as bb from table group by b havign count(1)>2
思路二:通过where 嵌套子查询
具体代码如下:
select a,b from table
where a in (select a from table group by a having count(1)>2)
or b in (select b from table group by b having count(1)>2);