简体   繁体   中英

get 2 record from each category doctrine query builder

Lets say I have the following table

-----------------------------
| user_id   | comment       |
-----------------------------
| 2         | thats cool    |
| 2         | awesome       |
| 3         | i hate this   |
| 3         | okay          |
| 6         | this is weird |
| 6         | hello?        |
| 6         | what is it    |
| 9         | how are you   |
| 16        | too slow      |
| 16        | yes           |
| 17        | alrighty      |
-----------------------------

How can you select two rows per user_id? So my results would be:

-----------------------------
| user_id   | comment       |
-----------------------------
| 2         | awsome        |
| 2         | thats cool    |
| 3         | i hate this   |
| 3         | okey          |
| 6         | this is weird |
| 6         | hello?        |
| 9         | how are you   |
| 16        | too slow      |
| 16        | yes           |
| 17        | alrighty      |
-----------------------------

Is this possible with a single efficient query? Or are sub-selected necessary?

SELECT user_id,
       comment
FROM
(
SELECT user_id,
       comment,
       CASE WHEN @user_id = T.user_id THEN 
       @ROW:=@ROW+1
       ELSE
       @ROW:=1
       END ROW,
       @user_id:=T.user_id
FROM 
Table1 T
,(SELECT @ROW=1,@user_id=null) R)
AS T1 WHERE ROW <=2

OUTPUT

user_id comment
2       thats cool
2       awesome
3       i hate this
3       okay
6       this is weird
6       hello?
9       how are you
16      too slow
16      yes
17      alrighty

Live Demo

http://sqlfiddle.com/#!9/c31356/4

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