MySQl查询选择限制中具有相同值的所有行,以便不会超出定义的限制值

时间:2013-04-04 09:27:11

标签: mysql

╔════════╦═══════════╦═══════╗
║ MSG_ID ║ RANDOM_ID ║  MSG  ║
╠════════╬═══════════╬═══════╣
║      1 ║        22 ║ apple ║
║      2 ║        22 ║ bag   ║
║      3 ║         0 ║ cat   ║
║      4 ║         0 ║ dog   ║
║      5 ║         0 ║ egg   ║
║      6 ║        21 ║ fish  ║
║      7 ║        21 ║ hen   ║
║      8 ║        20 ║ glass ║
╚════════╩═══════════╩═══════╝

想要以很多方式获取3条记录,以便拾取特定random_id的所有数据。

需要的结果:

║ MSG_ID ║ RANDOM_ID ║  MSG  ║
╠════════╬═══════════╬═══════╣
║      1 ║        22 ║ apple ║
║      2 ║        22 ║ bag   ║
║      3 ║         0 ║ cat   ║

当前结果:

║ MSG_ID ║ RANDOM_ID ║  MSG  ║
╠════════╬═══════════╬═══════╣
║      1 ║        22 ║ apple ║
║      3 ║         0 ║ cat   ║
║      4 ║         0 ║ dog   ║
______________________________

使用的查询:

SELECT  ID,Random_ID, GROUP_CONCAT(message SEPARATOR ' ' ),FLAG,mobile,sender_number,SMStype  
FROM    messagemaster
WHERE   Random_ID > 0
GROUP   BY Random_ID
UNION
SELECT  ID,Random_ID, message,FLAG,mobile,sender_number,SMStype
FROM    messagemaster
WHERE   Random_ID = 0
order by random_id LIMIT 100;

我不想使用group by来获取记录。我想通过random_ids获取所有记录。如果有一个random_id,其中有3条记录,如果查询的limit = 3,那么我希望拾取那些random_id的所有数据。 情况是,如果我获取限制为100的行,我不希望选择结果集中存在随机ID的某些数据。 例如,如果我为random id=22选择记录限制为3,则应选择random id =22的所有记录。

1 个答案:

答案 0 :(得分:0)

考虑以下内容......

 SELECT b.*
   FROM
      ( SELECT x.*, SUM(y.cnt)
          FROM 
             ( SELECT random_id,COUNT(*) cnt FROM messagemaster GROUP BY random_id) x
          JOIN
             ( SELECT random_id,COUNT(*) cnt FROM messagemaster GROUP BY random_id) y
            ON y.random_id >= x.random_id
         GROUP 
            BY x.random_id
        HAVING SUM(y.cnt) < 4
      ) a
   JOIN messagemaster b
     ON b.random_id = a.random_id;