Mysql

如何將 GROUP_CONCAT 用於列和 COUNT(*)?

  • December 15, 2021

我通過 獲取查詢的 ID GROUP_CONCAT

SELECT GROUP_CONCAT(ArticleID) FROM TagMap WHERE Tag IN(...)

如何將此查詢與COUNT(*)組合併

SELECT ArticleID,COUNT(*) FROM TagMap WHERE Tag IN(...) GROUP BY ArticleID

得到GROUP_CONCAT(ArticleID)訂單COUNT(*)

換句話說,在第一個查詢中,我想GROUP_CONCAT(ArticleID)按每個找到的標籤數量進行排序ArticleID

這會有所幫助,試一試

SELECT GROUP_CONCAT(ArticleID)
  ,COUNT(1) AS CNT
FROM (SELECT Tag
        ,ArticleID
        ,COUNT(1) AS CNT
 FROM TagMap Tag IN (...)
 GROUP BY Tag
          ,ArticleID) tmp
 GROUP BY Tag
 ORDER BY cnt

查詢可以是下一個:

SELECT 
   -- here we concatenate articles by tags count 
   GROUP_CONCAT(ArticleID ORDER BY cnt DESC) 
FROM (
 -- here we calculate different tags cout per article
 SELECT ArticleID, COUNT(DISTINCT Tag) cnt
 FROM TagMap 
 WHERE Tag IN('Tag1', 'Tag2', 'Tag3')
 GROUP BY ArticleID
) t;

這裡的工作範例:SQLize.online

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