SELECT 列不同于 GROUP BY 列

SELECT columns different from GROUP BY columns

具有此数据库模式(仅用于说明目的)

[articles (id_article, title)] 
[articles_tags (id_tag, id_article)]
[tags (id_tag, name)]

使用 MySQL 可以做到:

SELECT a.title, COUNT(at.id_tag) tag_count FROM articles a
JOIN articles_tags at ON a.id_article = at.id_article
JOIN tags t ON t.id_tag = at.id_tag
GROUP BY a.id_article
ORDER BY tag_count DESC

导致每行文章标题和文章标签计数的结果,例如

mysql for beginner | 8
ajax for dummies   | 4

由于 ORACLE 不支持 SELECT 语句中的 non-aggregated 列,是否可以在一个查询中以任何方式执行此操作?当您通过将聚合函数添加到 SELECT 语句或将列添加到 GROUP BY 语句来满足 ORACLE 的需求时,您已经得到了不同的结果。

提前致谢

是的,这是可能的。 Return id_article 在 SELECT 列表中,而不是 title,并将整个查询包装在括号中以使其成为内联视图,然后从中 select , 并加入 articles table 以获得关联的 title.

例如:

SELECT b.title
     , c.tag_count
  FROM ( SELECT a.id_article
              , COUNT(at.id_tag) tag_count 
           FROM articles a
           JOIN articles_tags at ON a.id_article = at.id_article
           JOIN tags t ON t.id_tag = at.id_tag
          GROUP BY a.id_article
       ) c
  JOIN articles b
    ON b.id_article = c.id_article
 ORDER BY c.tag_count DESC

您还可以评估您是否真的需要内联视图中包含的 articles table。我们可以改为 GROUP BY at.id_article

我认为这 returns 等效结果:

SELECT b.title
     , c.tag_count
  FROM ( SELECT at.id_article
              , COUNT(at.id_tag) tag_count 
           FROM articles_tags at
           JOIN tags t ON t.id_tag = at.id_tag
          GROUP BY at.id_article
       ) c
  JOIN articles b
    ON b.id_article = c.id_article
 ORDER BY c.tag_count DESC