添加连接时SQL行消失

时间:2011-02-23 10:37:23

标签: sql inner-join

SELECT     tblArtworkTemplates.ID, tblArtworkTemplates.dateCreated, tblSpecifications.TxtPagination, tblSpecifications.FlatSizeW AS width, 
                      tblSpecifications.FlatSizeL AS length, tblSpecifications.FlatSizeUOM AS uom,
                          (SELECT     COUNT(1) AS Expr1
                            FROM          tblArtworkUploads
                            WHERE      (templateID = tblArtworkTemplates.ID)) AS uploadCount,
                          (SELECT     COUNT(1) AS talks
                            FROM          tblArtworkTemplateMessages
                            WHERE      (templateID = tblArtworkTemplates.ID)) AS talkCount, tblArtworkTemplates.lastEditPing, tblUsers.userName AS Expr1
FROM         tblUsers INNER JOIN
                      tblArtworkTemplates INNER JOIN
                      tblSpecifications ON tblArtworkTemplates.specID = tblSpecifications.id ON tblUsers.id = tblArtworkTemplates.editPingUserID
WHERE     (tblArtworkTemplates.userID = 70)

当tbl Artwork Templates.editPing UserID为null时,tblusers join会导致行消失。我使用了错误的连接类型吗?

3 个答案:

答案 0 :(得分:3)

也许尝试左外连接..或右外连接..

Wikipedia了解有关加入

的信息

答案 1 :(得分:2)

试试这个,你的加入是错误的。

SELECT     tblArtworkTemplates.ID, tblArtworkTemplates.dateCreated, tblSpecifications.TxtPagination, tblSpecifications.FlatSizeW AS width, 
                      tblSpecifications.FlatSizeL AS length, tblSpecifications.FlatSizeUOM AS uom,
                          (SELECT     COUNT(1) AS Expr1
                            FROM          tblArtworkUploads
                            WHERE      (templateID = tblArtworkTemplates.ID)) AS uploadCount,
                          (SELECT     COUNT(1) AS talks
                            FROM          tblArtworkTemplateMessages
                            WHERE      (templateID = tblArtworkTemplates.ID)) AS talkCount, tblArtworkTemplates.lastEditPing, tblUsers.userName AS Expr1
FROM tblUsers u 
    INNER JOIN tblArtworkTemplates a ON  u.id = a.editPingUserID
    INNER JOIN tblSpecifications s ON a.specID = s.id ON
WHERE     (a.userID = 70)

答案 2 :(得分:1)

这取决于你的目标。

如果你总是想要来自tblUsers的记录,但是只有来自的数据来自Template + Specification的数据(换句话说,如果模板没有规范,你就不关心模板了),使用此

FROM tblUsers
LEFT JOIN
        tblArtworkTemplates
        INNER JOIN tblSpecifications
            ON tblArtworkTemplates.specID = tblSpecifications.id
    ON tblUsers.id = tblArtworkTemplates.editPingUserID

如果您总是需要来自tblUsers的记录,但是来自模板的数据(如果可用),然后来自规范(如果可用)(换句话说,如果模板可用没有规范,则无论如何从模板记录中获取数据) ,然后使用此

FROM tblUsers
LEFT JOIN
        tblArtworkTemplates
        LEFT JOIN tblSpecifications
            ON tblArtworkTemplates.specID = tblSpecifications.id
    ON tblUsers.id = tblArtworkTemplates.editPingUserID

或更常见的写法(因为2个左连接是可交换的)

FROM tblUsers
LEFT JOIN tblArtworkTemplates
    ON tblUsers.id = tblArtworkTemplates.editPingUserID
LEFT JOIN tblSpecifications
    ON tblArtworkTemplates.specID = tblSpecifications.id