我有一个关于编程论坛的项目。
我在数据库中有 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
这是正确的查询,但我想要更准确,帮助!