选择最多2行,其中列具有相同的值

Cal*_*cet 5 mysql sql

我试图选择最多2行,其中列具有相同的值.即:

id  title   accountid   date
1   job 1       1      Oct. 1
2   job 2       1      Oct. 1
3   job 3       1      Oct. 1
4   job 1       2      Oct. 2
5   job a       3      Oct. 2
6   job z       4      Oct. 3
7   job 2       2      Oct. 3
8   job 3       2      Oct. 8
Run Code Online (Sandbox Code Playgroud)

我想选择

    1   job 1       1      Oct. 1
    2   job 2       1      Oct. 1
                                   <----- Skip this row because we already 
                                          have 2 from account 1
    4   job 1       2      Oct. 2
    5   job a       3      Oct. 2
    6   job z       4      Oct. 3
    7   job 2       2      Oct. 3
Run Code Online (Sandbox Code Playgroud)

我现在正在使用的选择是这样的:

SELECT * 
FROM table 
ORDER BY date DESC, RAND() 
Run Code Online (Sandbox Code Playgroud)

我看起来有点使用,HAVING COUNT(accountid) <= 2但这只是导致混乱.我很擅长使用sql.

谢谢你的帮助!

更新:

嗨,谢谢你的所有快速反应.我已经尝试了他们每个人,似乎无法让他们工作.我想出了一种使用php限制每个帐户ID的作业的方法.再次感谢您花时间和精力帮我解决这个问题.

Clo*_*eto 2

set @id := 0, @acid := 0;
select t.id, title, accountid, `date`
from 
    t
    inner join (
        select 
            id, 
            if(@acid = accountid, @i := @i + 1, @i := 1) as i,
            @acid := accountid as acid
        from t
        order by accountid, `date` desc
    ) s on t.id = s.id
where s.i <= 2
Run Code Online (Sandbox Code Playgroud)