A
A
Alexander Verbitsky2019-04-02 03:52:22
MySQL
Alexander Verbitsky, 2019-04-02 03:52:22

How to select two records of a certain category from mysql database?

there is a table with goods.
5ca2b1b4d559f512707259.png
You need to select the first two records of each category with one query,
i.e. in the end it should turn out
5ca2b1ef93035827673023.png
PS If possible in yii2 format, if not, a simple mysql query will also go, I'll figure it out there =)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex, 2019-04-02
@streetflush

Select t1.cat_id, t1.id, t2.* from 
(Select cat_id, min(id) from table group by cat_id
UNION 
Select cat_id, min(id) from table
where id not in (Select min(id) from table group by cat_id) group by cat_id) t1
left join table t2 on t1.id = t2.id

MSSQL but I don't think it will be much different

K
Konstantin Tsvetkov, 2019-04-02
@tsklab

Several options .

R
retvizan, 2019-04-02
@retvizan

There are at least 6 solutions in 1 query, see Select multiple records from each group

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question