SQL Server使用另一个表加入结果

时间:2017-08-04 13:27:03

标签: sql sql-server

我正在尝试执行以下操作。

  • 加入2个表=>获得结果

第一次加入的结果我需要它加入另一张桌子

这就是我所拥有的

SELECT 
    T1.*, T2.*
FROM 
    (SELECT * 
     FROM ProductPackType ppt
     JOIN ProductPack pp ON ppt.ProductPackTypeID = pp.ProductPackTypeID
     WHERE pp.Acronym = 'IS') AS T1
JOIN 
    (SELECT * FROM PRODUCT) AS T2 ON T1.ProductPackID = T2.ProductPackID

这是错误消息

  

Msg 8156,Level 16,State 1,Line 10
  “T1”

多次指定“名称”列

我在这里做错了什么?

谢谢

3 个答案:

答案 0 :(得分:1)

ProductPackType和ProductPack表中都有列名。尝试类似:

SELECT 
    T1.*, T2.*
FROM 
    (SELECT ppt.Name, pp.Name as ppName --add the rest of your wanted columns...
     FROM ProductPackType ppt
     JOIN ProductPack pp ON ppt.ProductPackTypeID = pp.ProductPackTypeID
     WHERE pp.Acronym = 'IS') AS T1
JOIN 
    (SELECT * FROM PRODUCT) AS T2 ON T1.ProductPackID = T2.ProductPackID

正如你所看到的,我试图避免在T1表格中由于加入的查询而导致两列名称为' Name' (这里奇怪的文字游戏)。

你甚至可以写一些更短的东西:

SELECT ppt.*, pp.Name as ppName --and the rest of the pp columns

答案 1 :(得分:1)

为什么不忘记所有子查询的东西,只是一起加入表格?

SELECT * 
FROM ProductPackType ppt
JOIN ProductPack pp ON ppt.ProductPackTypeID = pp.ProductPackTypeID
JOIN PRODUCT p ON p.ProductPackID = ppt.ProductPackID
WHERE pp.Acronym = 'IS'

答案 2 :(得分:-1)

你可能有" name"来自" ppt"和" pp",尝试以下

SELECT 
    T1.*, T2.*
FROM 
    (SELECT ppt.*, pp.*
     FROM ProductPackType ppt
     JOIN ProductPack pp ON ppt.ProductPackTypeID = pp.ProductPackTypeID
     WHERE pp.Acronym = 'IS') AS T1
JOIN 
    (SELECT * FROM PRODUCT) AS T2 ON T1.ProductPackID = T2.ProductPackID