Limit query results to two rows per group

后端 未结 2 459
醉话见心
醉话见心 2021-01-27 22:49

I have a query to list all posts:

SELECT *, DATE(FROM_UNIXTIME(`timestamp`)) `date` 
FROM `posts`
ORDER BY `date` DESC

The query list all rows,

2条回答
  •  走了就别回头了
    2021-01-27 23:39

    I'm adapting a sql server/oracle solution to your world. Other column would be the ID of the table and then you could use that in a correlated subquery to get the rest of the columns. Let me know if it works for next time I use MySQL

    select l.DATE(FROM_UNIXTIME(`timestamp`)), l.`otherColumn`, count(*) as num
    from `posts` as l
    left outer join fruits as r
        on l.DATE(FROM_UNIXTIME(`timestamp`)) = r.DATE(FROM_UNIXTIME(`timestamp`))        
           and l.`otherColumn` >= r.`otherColumn`
    group by l.DATE(FROM_UNIXTIME(`timestamp`)), l.`otherColumn`
    having count(*) <= 2
    

提交回复
热议问题