MySQL SELECT 8个唯一用户,然后选择这8个用户中的所有记录,然后选择每8个用户中的4条最新记录和可用记录?

时间:2019-04-06 06:38:17

标签: mysql sql

我有一个数据库(出于订购目的,日期仅是示例)...

 ---------------------
| user | item |  date |
 ---------------------
|    1 |    a |   123 |
|    3 |    b |   124 |
|    1 |    c |   125 |
|    2 |    d |   126 |
|    5 |    i |   127 |
|    4 |    e |   128 |
|    6 |    f |   129 |
|    9 |    g |   130 | 
|    3 |    h |   131 |
|    9 |    s |   132 |
|    1 |    j |   133 |
|    2 |    k |   134 |
|    1 |    l |   135 |
|    1 |    m |   136 |
|    1 |    n |   137 |
|    8 |    o |   138 |
|    5 |    p |   139 |
|    9 |    q |   140 |
|    7 |    r |   141 |
 ---------------------

我希望所有记录都记录到前8个唯一用户的位置,从而得出结果...

 ---------------------
| user | item |  date |
 ---------------------
|    1 |    a |   123 |
|    3 |    b |   124 |
|    1 |    c |   125 |
|    2 |    d |   126 |
|    5 |    i |   127 |
|    4 |    e |   128 |
|    6 |    f |   129 |
|    9 |    g |   130 | 
|    3 |    h |   131 |
|    9 |    s |   132 |
|    1 |    j |   133 |
|    2 |    k |   134 |
|    1 |    l |   135 |
|    1 |    m |   136 |
|    1 |    n |   137 |
|    8 |    o |   138 |
 ---------------------

然后从这些记录中,我想获取每个唯一用户最近的4条记录 ,使结果看起来像...

 ---------------------
| user | item |  date |
 ---------------------
|    3 |    b |   124 |
|    2 |    d |   126 |
|    5 |    i |   127 |
|    4 |    e |   128 |
|    6 |    f |   129 |
|    9 |    g |   130 | 
|    3 |    h |   131 |
|    9 |    s |   132 |
|    1 |    j |   133 |
|    2 |    k |   134 |
|    1 |    l |   135 |
|    1 |    m |   136 |
|    1 |    n |   137 |
|    8 |    o |   138 |
 ---------------------

理想情况下,我可以使用一个查询来执行此操作。我最接近的查询是:

SELECT users, 
GROUP_CONCAT(items) 
FROM db 
GROUP BY users 
ORDER BY date 
LIMIT 8

但是GROUP_CONCAT会返回该用户的所有结果,而不仅仅是选择的数量。

我也尝试过...

SELECT users
FROM db AS u1
JOIN (SELECT DISTINCT users FROM db) AS u2 ON u1.users = u2.users

从我发现的另一个建议开始,但这还是行不通的。

我尝试了很多其他我没有真正节省的东西,因为它们没有用,我很确定自己会解决的,但是已经有两个星期了,而且我还没有接近。如果有任何SQL专家可以指出正确的方向,那将非常好。谢谢。

1 个答案:

答案 0 :(得分:0)

希望这可以为您提供帮助。

--get all records up to the first 8 unique users,depending on there first order date
 select distinct a.user,a.date as first_order_date from yourtable as a where 
 a.date = (select MIN(date) from yourtable as b where a.user=b.user) order by a.date LIMIT 8

然后使用上述结果为每个唯一用户获取最新的4条记录,如下所示:

select * from yourtable as t where t.date in 
(select date from yourtable as t2 where t.user=t2.user order by t2.date desc LIMIT 4 ) and 
t.user in (select distinct a.user,a.date as first_order_date from yourtable as a
where a.date = (select MIN(date) from yourtable as b where a.user=b.user) order by a.date LIMIT 8)

参考文献:

correlated subqueries

Example