簡體   English   中英

MySQl查詢選擇所有具有相同限制值的行,以確保沒有任何值超出定義的限制

[英]MySQl query Select all rows with same value in limit so that no value is left outside the limit defined

╔════════╦═══════════╦═══════╗
║ 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的某些數據。 例如,如果我將記錄限制限制為3,則對於random id=22 ,應選擇所有random id =22記錄。

考慮以下...

 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;

暫無
暫無

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

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