2

我有一个关于编程论坛的项目。

我在数据库中有 2 个表:

  • SUBJECT(idSUB,titleSUB);
  • TOPIC(idTOP, titleTOP, contentTOP, idSUB, idUser [用户创建主题], Time);

我想要的是:

+ select COUNT(*) from TOPIC as numTOPIC group by idSUB--> as Table A
+select TOP 1 titleTOP order by Time desc->  as newestTOP group by idSUB---> as Table B
+ Then JOIN 3 table A,B,SUBJECT--> C(idSUB,titleSUB,numTOPIC,newestTOP, idUser (who created the newest topic))

我找到了LEFT JOIN A, SUBJECT->的方法,C(idSUB,titleSUB,numTOPIC)但我真的不知道上面 JOIN 3 Tables 的正确语法。

SELECT  
    a.idSUB, a.titleSUB,
    COUNT(b.idSUB) numTOPIC 
FROM
    SUBJECT a
LEFT JOIN 
    TOPIC b ON a.idSUB = b.idSUB
GROUP BY 
    a.idSUB, a.titleSUB

我只想在一个查询中执行此操作。帮助!

更新:

通过@John Bingham 下面的代码,输出表无法显示SUBJECT没有任何TOPIC. 我想要所有的TOPIC都可以显示。

SELECT 
    s.idSUB, s.titleSUB, a.numTOPIC, 
    isnull(b.newestTOP, '') as [Newest Topic], 
    isnull(b.idUser, '')
FROM 
    Subject s 
INNER JOIN 
    (SELECT 
         IDSub, Count(*) as NumTopic 
     FROM 
         Topic 
     GROUP BY IDSub) a ON s.IDSub = a.IDSub
LEFT JOIN 
    (SELECT 
         t.IDSub, t.titleTop as newestTop, t.idUser as [idUser] 
     FROM 
         Topic t 
     INNER JOIN 
         (SELECT IDSub, Max([Time]) as tm 
          FROM Topic 
          GROUP BY IDSub) x ON t.IDSub = x.IDSub
     WHERE t.[Time] = x.tm) b ON s.IDSub = b.IDSub

这是正确的查询,但我想要更准确,帮助!

4

2 回答 2

1

我倾向于将每个需求 (a)、(b) 和 (c) 转换为子查询,这些子查询将虚拟表传递给您的查询,而不是尝试组合基表以一次性传递需求。所以 -

SELECT s.idSUB, s.titleSUB, a.numTOPIC, isnull(b.newestTOP, '') as [Newest Topic], 
  isnull(b.idUser, '')
FROM Subject s 
  INNER JOIN (SELECT IDSub, Count(*) as NumTopic FROM Topic GROUP BY IDSub) a 
    ON s.IDSub = a.IDSub
  LEFT JOIN (
    SELECT t.IDSub, t.titleTop as newestTop, t.idUser as [idUser] 
    FROM Topic t 
      INNER JOIN (
        SELECT IDSub, Max([Time]) as tm FROM Topic GROUP BY IDSub
      ) x ON t.IDSub = x.IDSub
    WHERE t.[Time] = x.tm
  ) b ON s.IDSub = b.IDSub
于 2013-09-25T05:11:01.213 回答
0

您想显示idSub, titleSub, numTopic, newestTOP,idUser其中numTopic是任何主题的主题数,即idSub同一newestTOP主题的最新主题。

我正在使用 MySQL 并测试了以下查询,它工作正常。

SELECT S.idSub, S.titleSUB, TOPIC_COUNT_TABLE.NUMTOPIC, NEWESTTOPIC_TABLE.NEWESTTOPIC,   
NEWESTTOPIC_TABLE.IDUSER 
FROM SUBJECT S,

(SELECT IDSUB, COUNT(*) AS NUMTOPIC FROM TOPIC 
GROUP BY TOPIC.IDSUB) AS TOPIC_COUNT_TABLE, 

(SELECT T.IDSUB,T.titleTOP AS NEWESTTOPIC, T.IDUSER  
FROM TOPIC T,(SELECT IDTOP,IDSUB,MAX(TIME) AS MAXTIME FROM TOPIC
GROUP BY IDSUB ) AS MAXTIME_TABLE
WHERE T.TIME = MAXTIME_TABLE.MAXTIME) AS NEWESTTOPIC_TABLE

WHERE S.IDSUB = NEWESTTOPIC_TABLE.IDSUB AND S.IDSUB = TOPIC_COUNT_TABLE.IDSUB;
于 2013-09-25T05:49:15.550 回答