MySQL 长难句分析

来源:互联网 发布:淘宝线下实体店加盟 编辑:程序博客网 时间:2024/05/02 20:45

/*原始数据*/

数据表pc:
3IBM80002564ASUS50005126hp700020008MAC1200040009lenovo5000200010MAC120002000

数据表phone:

1ipone50002huawei20003xiaomi10004meizu12345meizu56786meizu2000

select * from pc;


select * from phone;


# 显示phone中重复的条目,显示出来的条目的phone的字段的信息是id最小的那条条目的信息
select idphone, phone_name, phone_price from phone group by phone_name having count(phone_name) >= 2;


# 显示pc和phone中id相同的条目
select * from pc join (select idphone, phone_name, phone_price from phone /*having count(phone_name) >= 2*/) as test on pc.idpc = test.idphone order by idphone;


# 显示phone中重复的条目和重复次数
select *, count(d1.phone_name) as count from (phone as d1 left join (select phone.phone_name, phone.phone_price from phone) as d2 on d1.phone_name = d2.phone_name) group by d1.phone_name having count >= 2 order by d1.idphone;

# 显示phone和phone中重复条目 去掉下面的注释之后变成只显示一条
select */*, count(tele.phone_name)*/ from phone as com left join (select phone_name, idphone from phone group by phone_name having count(phone_name) >= 2) as tele on com.phone_name = tele.phone_name;


# phone(com)与phone(tele)中重复条目左连接,连接条件是com的phone_name与tele的phone_name相同。连接完了之后删除com中"满足条件:com中的idphone大于tele中的idphone的条目"的条目  操作完成的同时,com的类型,也就是数据表phone,也会对应删除com中被删除的条目。
delete com from (phone as com left join (select phone_name, idphone from phone group by phone_name having count(phone_name) >= 2) as tele on com.phone_name = tele.phone_name) where com.idphone > tele.idphone;


0 0
原创粉丝点击