我正在尝试选择最多 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
我要选择
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
我现在用来选择的是这样的:
SELECT *
FROM table
ORDER BY date DESC, RAND()
我研究了一下使用 HAVING COUNT(accountid) <= 2
但这只会导致困惑。我对使用 sql 还很陌生。
感谢您的帮助!
更新:
您好,感谢您的快速回复。我已经尝试了他们中的每一个,但似乎无法让他们工作。我想出了一种使用 php 来限制每个帐户 id 的作业的方法。再次感谢您花时间和精力帮助我解决这个问题。
最佳答案
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
关于mysql - 最多选择 2 行,其中一列具有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12845519/