Mysql

使用 WHERE 條件為每個 GROUP 選擇 n 行

  • September 12, 2021

表格中的每一個都在SELECTn 行中ArticleID``TagMap

SELECT a.ArticleID,a.TagID FROM TagMap a
LEFT JOIN TagMap b ON a.ArticleID = b.ArticleID AND a.TagID < b.TagID
GROUP BY a.ArticleID,a.TagID
HAVING COUNT(b.TagID) < 3
ORDER BY a.ArticleID,a.TagID

我想添加一個條件來限制查詢到特定的標籤,

SELECT a.ArticleID,a.TagID FROM TagMap a
 LEFT JOIN TagMap b ON a.ArticleID = b.ArticleID AND a.TagID < b.TagID
   WHERE a.TagID IN(SELECT TagID FROM Tags WHERE Status=1)
   AND b.TagID IN(SELECT TagID FROM Tags WHERE Status=1)
 GROUP BY a.ArticleID,a.TagID
 HAVING COUNT(b.TagID) < 3
 ORDER BY a.ArticleID,a.TagID

如果我使用條件作為子查詢,我需要子查詢。如果我使用條件 as JOIN,我需要兩個JOINs ,因為上面JOINLEFT JOIN

有更簡單的方法嗎?

您可以將狀態條件添加到 th on 子句

 SELECT a.ArticleID,a.TagID FROM TagMap a
     LEFT JOIN TagMap b ON a.ArticleID = b.ArticleID AND a.TagID < b.TagID AND a.Status =1 AND b.Status = 1
     GROUP BY a.ArticleID,a.TagID
     HAVING COUNT(b.TagID) < 3
     ORDER BY a.ArticleID,a.TagID

如果 a 狀態是獨立的,如果 a 或 b 佔據該行,則根本不需要子選擇,如果不是,則將其解僱。

如果將狀態條件放在 WHERE 子句或 ON 中,則不會更改執行計劃。

但是您可以更改索引以包含狀態

引用自:https://dba.stackexchange.com/questions/299411