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