5

我正在尝试选择最多 2 行,其中一列具有相同的值。IE:

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 的作业的方法。再次感谢您为帮助我解决此问题所付出的时间和努力。

4

3 回答 3

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
于 2012-10-11T17:59:03.653 回答
2

嗨,这会解决你的问题,但我不知道这个查询有多快。

SQLFIDDLE 示例

询问:

SELECT
id, 
title,
accountid,
date
FROM
    (SELECT
     IF(@prev != a.accountid, @rownum:=1, @rownum:=@rownum+1) as rownumber, 
     @prev:=a.accountid, 
     a.*
     FROM (
           SELECT 
           t1.id, 
           t1.title,
           t1.accountid,
           t1.date
           FROM tbl t1,
           (SELECT @rownum := 0, @prev:='') sq
              ORDER BY  accountid, id) a
    )b
WHERE b.rownumber<3
ORDER BY b.id

结果:

| ID | TITLE | ACCOUNTID |   DATE |
-----------------------------------
|  1 | job 1 |         1 | Oct. 1 |
|  2 | job 2 |         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 |
于 2012-10-11T21:07:30.750 回答
1
SELECT tab.id, tab.title, tab.accountid, tab.date
FROM table tab INNER JOIN table count_tab ON tab.id = count_tab.id
WHERE count_tab.id <= tab.id
GROUP BY tab.id, tab.title, tab.accountid, tab.date
HAVING count(count_tab.id) <= 2
于 2012-10-11T18:04:55.730 回答