[英]get 2 record from each category doctrine query builder
可以说我有下表
-----------------------------
| 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 |
-----------------------------
如何为每个user_id选择两行? 所以我的结果是:
-----------------------------
| 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 |
-----------------------------
一个有效的查询是否有可能? 还是需要子选择?
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
输出值
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
现场演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.