我有两个表:news
和comments
。
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)
)
有没有办法选择按照他们的评论数量排序的所有新闻?
答案 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