簡體   English   中英

最多選擇2行,其中一列具有相同的值

[英]Select a maximum of 2 rows where a column has the same value

我試圖選擇最多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

您好,這可以解決您的問題,但我不知道此查詢的速度如何。

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 |
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM