Mysql

如何在使用子查詢時將表與自身連接?

  • June 3, 2020

JOIN將自己的表作為

SELECT t1.TagID AS TagID1
   ,t2.TagID AS TagID2
   ,COUNT(1)
FROM TagMap AS t1
JOIN TagMap AS t2 ON t1.ArticleID = t2.ArticleID AND t1.TagID <> t2.TagID
GROUP BY t1.TagID, t2.TagID

如何通過以下方式限制為每個表(t1 和 t2)檢索的行

WHERE TagID IN(SELECT TagID FROM Tags WHERE Articles>50)

請注意,該表TagMap很大,行數超過 200M,我希望在JOIN.

其實我想限制行數的原因TagMap是表太大,無法執行JOIN

您使用子選擇查詢作為 t1 和 t2 的基礎

SELECT 
   t1.TagID AS TagID1, t2.TagID AS TagID2, COUNT(1)
FROM
   (SELECT 
       *
   FROM
       TagMap
   WHERE
       TagID IN (SELECT 
               TagID
           FROM
               Tags
           WHERE
               Articles > 50)) AS t1
       JOIN
   (SELECT 
       *
   FROM
       TagMap
   WHERE
       TagID IN (SELECT 
               TagID
           FROM
               Tags
           WHERE
               Articles > 50)) AS t2 ON t1.ArticleID = t2.ArticleID
       AND t1.TagID <> t2.TagID
GROUP BY t1.TagID , t2.TagID

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