First of all, note that taking the largest data in each group and taking the largest record in each group are two concepts. The former is very simple and directly grouped, and max() is enough.
sql is as follows
SELECT *, max(hash) FROM log GROUP BY code
Go back and get the * content of the first piece of data in the group, and then append the result obtained by max, but the result does not match that piece of data
That is, only the largest data of each group is taken out (if you only need the largest data, you can change the sql to satisfy, if you want to remove the record with the largest data, you cannot simply use this sql)
1. Sort first and then group
Then it is natural to think of using select * from log order by hash desc to sort it in reverse order
According to the idea, then treat the above as a subquery
select * from (select * from log order by hash desc) as a group by code
After checking the data, it turns out that limit must be added after sorting. If not, the data will not be sorted first. so
select * from (select * from log order by hash desc limit 10000 ) as a group by code
2. The subquery part uses group by grouping to find the largest of each group, and the outer query uses multi-field in query.
select * from log where(code,hash) in (SELECT code,max(hash) hash FROM log group by code)
A question in leetcode saw the usage of in in two fields
https://leetcode-cn.com/problems/department-highest-salary/
3. Fanwai (obtain the id of the individual data through max to check the corresponding data according to the id)
single table query:
the one with the smallest id, the simplest statement is:
select * from table order by id
If you must use the where condition, you can write it like this:
select * from table where id=(select min(id) from table)
3.1 Extra 2
Table A is the product table,
table B is the sku table, (each product has multiple sku (specifications))
query all the products and the whole piece of data with the smallest sku price in each product
select
A.id,A.goodsname as title,A.norms,A.status as gstatus,A.imgurls,A.uppertime,A.downtime,A.createtime as gcreatetime,A.updatetime as gupdatetime, A.isteam,B.id as defaultsku,B.price as minprice,B.preprice
from A
INNER JOIN B on A.id=B.goodsid
where B.price = ( select min(B.price) from B where B.goodsid=A.id)
and A.status=1 and B.status=1
group by A.id
order by A.id desc
————————————————
Copyright statement: This article is an original article of CSDN blogger "solmee", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/weixin_40024174/article/details/99462595