【问题标题】:how to get a single row for each user?如何为每个用户获取一行?
【发布时间】:2013-05-29 09:56:47
【问题描述】:

对不起标题,我不知道如何更好地解释它......

我有一个论坛,我想用 php 制作一种成就系统

我想知道有帖子的用户何时发布了他们的第 10 条消息...

post 表是这样的

post_id | post_date | userid | post_message | ...

我可以为每个用户得到这个结果

select userid, post_date from posts where userid=1 order by post_date limit 9,1

但我需要一个类似的结果集

id | date
id | date
id | date

只能通过程序来完成?

【问题讨论】:

  • 你想要eash用户的第10个帖子吗??
  • 你在寻找的字段标题应该不同吗?

标签: mysql sql limit forum


【解决方案1】:

试试这个查询

select 
    * 
from (
    select 
       @rn:=if(@prv=userid, @rn+1, 1) as rid, 
       @prv:=userid as userid,
       post_message
    from 
       tbl
    join 
       (select @rn:=0, @prv:=0) tmp
    order by 
       userid, 
       post_date) tmp 
where 
    rid=10

SQL FIDDLE

| RID | USERID | POST_MESSAGE |
-------------------------------
|  10 |      1 |       asdasd |
|  10 |      2 |       asdasd |

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT userid
        , SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(post_date ORDER BY post_date), ',', 10), ',', -1) AS PostDate
        FROM posts
        GROUP BY userid
        HAVING PostDate <> '' OR PostDate IS NOT NULL
    

    但是你需要注意GROUP_CONCAT可以容纳的最大长度。

    【讨论】:

    • 由于可靠性,这比使用用户变量的解决方案要好,但是您需要过滤掉少于 10 个帖子的用户 ID,因为 substring_index 将为他们返回最后一个。所以你需要HAVING count(*) &gt;= 10
    • 嗨@piotrm,我已经有HAVING PostDate &lt;&gt; '',它可以消除少于10个帖子的用户。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2020-04-06
    相关资源
    最近更新 更多