问题:把衣服、裤子、裤子、鞋子这些类别中点击量最高的一条记录找出来,并按降序排列!
![](https://img.haomeiwen.com/i5336223/5791b7f82d568e87.png)
![](https://img.haomeiwen.com/i5336223/203fd7d7fda487a6.png)
解题思路:
1. 审题(需要用到的SQL语句)
“衣服、裤子、帽子、鞋子这些类别”:进行分组 group by
“点击量最高”:复合函数 Max()
“降序排列”:排序关键字 order by 降序 desc
需要显示出来的字段:productID,productName,最高 clickNum
2. SQL语句分解
方法1:
首先,�查询出点击量最高的parentID,并将查询结果取别名为b表
select parentid, max(clicknum) clicknum FROM productinfo GROUP BY parentid
查询结果如图:b 表
![](https://img.haomeiwen.com/i5336223/1fb3e391ab4b4d46.png)
查询出表中的productid, productname, clicknum相关数据,取别名为a表:
ELECT productid, productname, clicknum FROM productinfo as a ;
![](https://img.haomeiwen.com/i5336223/3622a370306b1e2d.png)
从a、b表中查找parentid & clicknum 都相等的数据:
SELECT a.productid, a.productname, a.clicknum FROM productinfo a, b WHERE a.parentid = b.parentid AND a.clicknum = b.clicknum;
![](https://img.haomeiwen.com/i5336223/566150d9b7102dc9.png)
具体SQL图& SQL语句如下:
![](https://img.haomeiwen.com/i5336223/a090fa67b5b39c71.png)
方法1 SQL如下
SELECT a.productid, a.productname, a.clicknum
FROM productinfo a,(
SELECT parentid, max(clicknum) clicknum
FROM productinfo GROUP BY parentid ) b
WHERE a.parentid = b.parentid AND a.clicknum = b.clicknum
ORDER BY a.clicknum DESC;
方法2:
![](https://img.haomeiwen.com/i5336223/fd14d9ccc4cc48a3.png)
方法2 SQL如下:
SELECT p.productid, p.productname, p.clicknum
FROM class c
JOIN (
SELECT * FROM productinfo p WHERE clicknum = (
SELECT max(clicknum) FROM productinfo
WHERE parentid = p.parentid )
) p ON c.classid = p.parentid
ORDER BY p.clicknum DESC;
方法3:
新建表a1: select * from productinfo a1
![](https://img.haomeiwen.com/i5336223/9dcb2598ac603f82.png)
找出productinfo表中 parentid与a表中相等,clicknum比a表中大的数据:
select 1 from productinfo where a1.parentid = parentid and a1.clicknum < clicknum 查找出来的结果相当于又新建了一张表,即下面的 c 表。
为方便理解,将两表放一起(数据都是一样的):
![](https://img.haomeiwen.com/i5336223/685453f18688fa63.png)
得到的结果如下,相当于又一个新表,为方便理解起名为 c 表:
![](https://img.haomeiwen.com/i5336223/342b17f8579da9fa.png)
从productinfo表中找c表中没有的数据:
select * from productinfo a where not exists c
![](https://img.haomeiwen.com/i5336223/1319df54dd8b5ecc.png)
方法3 SQL如下:
select * from productinfo a
where not exists (
select 1 from productinfo
where
a.parentid = parentid
and clicknum > a.clicknum
)
order by clicknum desc;
方法4:
简单数据
![](https://img.haomeiwen.com/i5336223/f2bf95f569ad92e7.png)
当新增一条特殊记录
insert into productInfo (productID, productName, parentID, clickNum) values (10,'女士鞋子1',10,30);
再次查询
select * from productinfo where clicknum in (select max(clickNum) from productinfo group by parentid) order by clicknum desc;
结果
![](https://img.haomeiwen.com/i5336223/1f958d5354d4e147.png)
使用in贪婪匹配,再次查询
select * from productInfo
where (clickNum, parentID)
in (select max(clickNum),parentID from productInfo group by parentId)
order by clickNum desc
![](https://img.haomeiwen.com/i5336223/e28b384cfe3c91db.png)
这样就去除了 parentID的 Max clickNum与另一种parentID 非 Max clickNum相同的特殊情况
网友评论