简体   繁体   中英

Explain the query to select the first two records of each group by a “SELECT” command

I have find an answer to my query problem from Solution However, I am problem in understanding the logic of the query. Can anyone help me understand this query?

Query:

select a.*
from Tablename a
where 
(
   select count(*) 
   from Tablename as b
   where a.group = b.group and a.id >= b.id
) <= 2

Mysql will first form the query op of

select count(*) 
   from Tablename as b
   where a.group = b.group and a.id >= b.id

this will count the record of table name Tablename on condition that a.group column value is equal to b.group column value and a.id 's value greater than b.id 's value, it will count the record which satisfy this condition.

then it passes it to main / parent query it's op. now parent query will count the record from Tablename on condition that subquery 's op less than or equal to 2 .

And why are you querying on same table (in main + sub query) ? and where's the b.group came from ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM