加入3张不同FK的牌桌

时间:2016-09-17 01:52:04

标签: sql join foreign-keys inner-join foreign-key-relationship

我试图在一个带有一些WHERE子句的SELECT查询中连接3个表。 表1与表2相关,表2与表3相关联。

表格如下:

Author
PK: Author_ID
FK: Location_ID
Author_First_Name

Location
PK: Location_ID
City

Articles
PK: Article_ID
FK: Author_ID
Article_Name

到目前为止,我已将此查询整理在一起,但我无法确定如何加入第二个外键' Location_ID'

SELECT 
    Articles.Article_Name 
FROM 
    Articles
        INNER JOIN Author
            ON Articles.Author_ID
        INNER JOIN Location
            ON 
WHERE Author.Author_First_Name='Sam'
AND Location.City<>'Detroit'

2 个答案:

答案 0 :(得分:1)

正确的语法是这样的:

SELECT a.Article_Name
FROM Articles a INNER JOIN
     Author au 
     ON a.Author_ID = au.Author_ID INNER JOIN
     Location l
     ON l.Location_ID = au.Location_Id
WHERE au.First_Name = 'Sam' AND l.City <> 'Detroit';

请注意,使用表别名可以使查询更易于编写和读取。此外,您需要连接ON子句的两个表的条​​件。

答案 1 :(得分:0)

您忘记比较表格字段

SELECT * FROM articles ar
LEFT JOIN author a ON ar.author_id = a.author_id
LEFT JOIN location l ON a.location_id = l.location_id
WHERE a.author_first_name = 'Sam' AND l.city <> 'Detroit'