如何连接具有多个相关列的两个表?

时间:2016-02-03 23:20:54

标签: sql sql-server

我想我正在问正确的问题,但是在我对你的帖子进行投票之前,让我告诉你我的代码:

SELECT  co_ship.ship_date,
        co_ship.co_num,
        co.whse,
        co_ship.qty_shipped * co_ship.price,
        co_ship.price,
        co_ship.qty_shipped,
        co.cust_num

FROM    coitem, co_ship, co 

WHERE   co.co_num = coitem.co_num AND coitem.co_release = co_ship.co_release AND coitem.co_line = co_ship.co_line AND coitem.co_num = co_ship.co_num

我想要做的是摆脱WHERE语句并用JOIN替换它。 (是的,我意识到我的代码可能非常错误)以下是我正在尝试的内容:

SELECT  co_ship.ship_date,
    co_ship.co_num,
    co.whse,
    co_ship.qty_shipped * co_ship.price,
    co_ship.price,
    co_ship.qty_shipped,
    co.cust_num

FROM    coitem, co_ship, co 

JOIN    co
ON      coitem.co_num = co.co_num 

JOIN    coitem
ON      co_ship.co_release=coitem.co_release AND co_ship.coline=coitem.co_line AND co_ship.co_num=co_item.co_num  

然而,这不起作用。我收到了这个错误:"对象" co"和" co" FROM子句中具有相同的公开名称。使用相关名称来区分它们。"

我不完全确定如何解决它。

1 个答案:

答案 0 :(得分:2)

使用显式连接语法时,您不希望有多个项目作为源;其余的应该出现在连接中(所以没有from table1, table2, ...

您的联接应该看起来很像:

FROM    coitem
JOIN    co_ship 
    ON coitem.co_release = co_ship.co_release 
   AND coitem.co_line    = co_ship.co_line 
   AND coitem.co_num     = co_ship.co_num
JOIN    co ON co.co_num = coitem.co_num 

所以请从co_ship子句中删除cofrom