SQL Server INNER JOIN有三个表

时间:2015-04-14 08:48:07

标签: sql asp.net sql-server

我有以下表结构:

新闻(Id_news,news_name)

评论(Id_comment(PK),Id_news(FK),评论)

回复(Id_Reply(PK),Id_Comment(FK),回复)


我想获得新闻中评论的回复数量。

这是我试过的查询。

SELECT COUNT(*)
FROM (News INNER JOIN Comments ON News.Id_news = Commnets.Id_Comment)
INNER JOIN Reply ON Commnets.Id_Comment = Reply.Id_Comment
WHERE News.Id_news = {0}

这有以下几种情况:我有一个网页上有很多新闻,但并非所有新闻都有评论而且并非所有评论都有回复。所以我需要计算一下特定新闻中是否有任何回复(例如Id_news = 43),以运行一个或另一个代码。

3 个答案:

答案 0 :(得分:4)

正如您所提到的,您希望对任何可能有或没有任何评论或回复的特定新闻进行回复。这是我的尝试

SELECT COUNT(Replys.Id_Reply)
FROM NEWS  
LEFT JOIN Coments  ON Coments.ID_News = Coments.Id_News AND NEWS.Id_News = {0}
LEFT JOIN Replys  ON Replys.Id_Comment = Coments.Id_Comment

尝试的示例代码

CREATE TABLE NEWS (Id_news INT, news_name varchar(10))
CREATE TABLE Coments (Id_comment INT,Id_news INT, comment varchar(10))
CREATE TABLE Replys(Id_Reply INT, Id_Comment INT , reply varchar(10))

INSERT INTO NEWS VALUES (1,'News1'), (2, 'News2'), (3,'News3')
INSERT INTO Coments VALUES (1,1,'Comment1'), (2,1,'Comment2'), (3,2,'Comment3')
INSERT INTO Replys VALUES (1,1,'Reply1'),(2,3,'Reply2'), (3,3,'Reply3')

<强>查询

DECLARE @NewId INT = 2
SELECT COUNT(Id_Reply)
FROM NEWS N 
LEFT JOIN Coments C ON C.ID_News = N.Id_News AND N.Id_News = @NewId
LEFT JOIN Replys R ON R.Id_Comment = C.Id_Comment

检查SQL Fiddle

答案 1 :(得分:0)

试试这个..

SELECT   News.Id_news,COUNT(*)
FROM    News 
JOIN    Comments 
    ON  News.Id_news = Commnets.Id_news
JOIN    Reply       
    ON  Commnets.Id_Comment = Reply.Id_Comment
WHERE   News.Id_news = {0}
group by News.Id_news,Commnets.Id_Comment

答案 2 :(得分:0)

我认为您在第一次加入时加入了错误的ID。尝试

SELECT 
    COUNT(*)
FROM 
    News JOIN Comments ON News.Id_news = Commnets.Id_news
        JOIN Reply ON Commnets.Id_Comment = Reply.Id_Comment
WHERE 
    News.Id_news = {0}