Oracle选择了大多数评论的新闻

时间:2015-04-16 05:58:34

标签: sql oracle select

我有两个表:newscomments

News表:

CREATE TABLE "NEWS"
(
  "NEWS_ID"           NUMBER(20, 0),
  "SHORT_TEXT"        VARCHAR2(100 BYTE),
  "FULL_TEXT"         VARCHAR2(2000 BYTE),
  "TITLE"             VARCHAR2(30 BYTE),
  "CREATION_DATE"     TIMESTAMP(6),
  "MODIFICATION_DATE" DATE
)

Comments表:

CREATE TABLE "COMMENTS"
(
  "COMMENT_ID"    NUMBER(20, 0),
  "COMMENT_TEXT"  VARCHAR2(100 BYTE),
  "CREATION_DATE" TIMESTAMP(6),
  "NEWS_ID"       NUMBER(20, 0)
)

有没有办法选择按照他们的评论数量排序的所有新闻?

1 个答案:

答案 0 :(得分:3)

您可以使用对评论数量的汇总查询加入新闻表:

SELECT    news.*, NVL(num_comments, 0) AS num_comments
FROM      news
LEFT JOIN (SELECT   news_id, COUNT(*) AS num_comments
           FROM     comments
           GROUP BY news_id) cmt on cmt.news_id = news.news_id
ORDER BY  num_comments DESC