当1个表为空时,SQL连接3个表

时间:2010-03-17 13:23:45

标签: sql mysql join

我正在尝试编写一个连接3个表的查询。

第一张表是关于每个节日的信息。 第二张表是每个节日的投票数。 第三张表是每个节日的评论。

我想加入所有3个表,所以我从table1获取所有列,在tableid上将table1与table2连接,但我还需要计算表3中适用于每个节日的记录数。

前两个表给我一个结果,因为它们都有数据但是表3是空的,因为还没有评论,所以将它添加到我的查询中没有给我任何结果。

SELECT  f.*,
        v.total,
        v.votes,
        v.festivalid,
        r.reviewcount as count
    FROM festivals f
INNER
    JOIN vote v
        ON f.festivalid = v.festivalid
INNER 
    JOIN (SELECT festivalid,
                 count(*) as reviewcount
            FROM reviews)
            GROUP BY festivalid) as r

        on r.festivalid = v.festivalid

4 个答案:

答案 0 :(得分:3)

LEFT OUTER JOIN

e.g。

SELECT  f.*, 
        v.total, 
        v.votes, 
        v.festivalid, 
        r.reviewcount as count 
    FROM festivals f 
INNER 
    JOIN vote v 
        ON f.festivalid = v.festivalid 
LEFT OUTER
    JOIN (SELECT festivalid, 
                 count(*) as reviewcount 
            FROM reviews 
            GROUP BY festivalid) as r 

        on r.festivalid = v.festivalid 

答案 1 :(得分:2)

SELECT  f.*,
        v.total,
        v.votes,
        v.festivalid,
        ifnull(r.reviewcount,0) as count
    FROM festivals f
INNER
    JOIN vote v
        ON f.festivalid = v.festivalid
LEFT OUTER 
    JOIN (SELECT festivalid,
                 count(*) as reviewcount
            FROM reviews)
            GROUP BY festivalid) as r

        on r.festivalid = v.festivalid

添加ifnull以将评论显示为0,以防没有。

答案 2 :(得分:1)

第二个连接不应该是内连接。

SELECT  f.*,
            v.total,
            v.votes,
            v.festivalid,
            r.reviewcount as count
        FROM festivals f
    INNER
        JOIN vote v
            ON f.festivalid = v.festivalid
    LEFT OUTER
        JOIN (SELECT festivalid,
                     count(*) as reviewcount
                FROM reviews
                GROUP BY festivalid) as r

            on r.festivalid = v.festivalid

关于外连接的文章: http://msdn.microsoft.com/en-us/library/ms187518.aspx

答案 3 :(得分:0)

尝试在审核计数表(r)上使用外部联接

SELECT  f.*,
        v.total,
        v.votes,
        v.festivalid,
        r.reviewcount as count
    FROM festivals f
INNER
    JOIN vote v
        ON f.festivalid = v.festivalid
LEFT OUTER
    JOIN (SELECT festivalid,
                 count(*) as reviewcount
            FROM reviews)
            GROUP BY festivalid) as r
        on r.festivalid = v.festivalid