获取具有唯一值的已排序mysql记录

时间:2016-11-23 00:40:58

标签: php mysql

我正在尝试从数据库中获取一些值,但是将其限制为每个帐户1,并且我无法按照我想要的方式运行它。

以下是查询,以正确的顺序获取电子邮件,并忽略该帐户:

SELECT ID FROM MailSent 
    WHERE DateSent IS NULL AND Valid = 1 ORDER BY Priority DESC LIMIT 14

我希望每个帐户(EmailID)具有最高优先级记录。我可以循环遍历结果并丢弃任何重复项,但实际限制将比预期的限制低很多。

以下是我尝试过的一些事情:

SELECT ID, DISTINCT(EmailID) FROM MailSent
    WHERE DateSent IS NULL AND Valid = 1 ORDER BY Priority DESC LIMIT 14
// error

SELECT DISTINCT(EmailID), ID FROM MailSent
    WHERE DateSent IS NULL AND Valid = 1 ORDER BY Priority DESC LIMIT 14
// still has duplicates

SELECT ID FROM MailSent 
    WHERE DateSent IS NULL AND Valid = 1 ORDER BY Priority DESC GROUP BY EmailID LIMIT 14
// error

SELECT ID FROM MailSent
    WHERE DateSent IS NULL AND Valid = 1 GROUP BY EmailID ORDER BY Priority DESC LIMIT 14
// wrong priority

作为奖励,但不是必需的,因为它可能很难做到,将它限制在用户定义的数量而不仅仅是1时会很好。

1 个答案:

答案 0 :(得分:1)

只需使用变量

SELECT ID, EmaailID
FROM (
       SELECT ID, EmailID,
              @rn := if(@email = EmailID,
                        @rn + 1,
                        if(@email := EmailID, 1, 1)
                       ) as rn
       FROM MailSent 
       CROSS JOIN (SELECT @email := 0, @rn := 0) as param
       WHERE DateSent IS NULL AND Valid = 1
       ORDER BY Priority Desc
       ) T
WHERE T.rn = 1

现在,如果您想为用户提供限制结果,则需要设置表或来自某个地方的查询。只需将以前的WHERE替换为:

   JOIN (SELECT userID, numberofRows
         FROM SettingTable) P
     ON T.ID = P.userID
    AND T.rn <= P.numberofRows