5

我有 2 张桌子

requests( ID, company_id, amount)

companies( ID, name)

带有 FK 约束 ( requests.company_id-> companies.id)

requests.companyNULL

如果没有指定公司,我需要获取所有请求并替换company_id为适当的公司name或将其留空。

我有下一个查询:

SELECT R.[ID], C.[name] AS [company], R.[amount], ...
FROM [requests] AS R, [companies] AS C, ...
WHERE R.[company_id] = C.[ID]

并且它工作正常,直到 NULL 进入company字段。

我试着下一步做:

SELECT R.[ID], C.[name] AS [company], ...
FROM [requests] AS R, ...
LEFT OUTER JOIN [companies] AS C
ON R.[company_id] = S.ID

但是得到了

无法绑定多部分标识符“R.company_id”

ON子句转换中的字段也有同样的错误。我究竟做错了什么?

4

3 回答 3

9

您展示的代码示例有省略号,我相信是省略号中的内容导致了问题。

你有:

SELECT R.[ID], C.[name] AS [company], ...
FROM [requests] AS R, ...
LEFT OUTER JOIN [companies] AS C
ON R.[company_id] = S.ID

假设是这样的:

SELECT R.[ID], C.[name] AS [company], X.Field
FROM [requests] AS R, [eXample] as X 
LEFT OUTER JOIN [companies] AS C
ON R.[company_id] = S.ID
WHERE X.[request_id] = R.ID

换句话说,ANSI 92 之前的内连接语法与 ANSI 92 外连接语法的混合。在 SQL Server 2005 上进行测试时,在您的示例中,在将 R 与 ... 分开的逗号之后,似乎看不到请求的别名 R,而在我的示例中,[eXample] 为 X。然而,以下确实有效:

SELECT R.[ID], C.[name] AS [company], X.Field
FROM [eXample] as X, [requests] AS R 
-- Requests and companies on the same side of the comma
LEFT OUTER JOIN [companies] AS C
ON R.[company_id] = S.ID
WHERE X.[request_id] = R.ID

或者

SELECT R.[ID], C.[name] AS [company], X.Field
FROM [requests] AS R LEFT OUTER JOIN [companies] AS C
    ON R.[company_id] = S.ID, [eXample] as X 
WHERE X.[request_id] = R.ID
-- Yuck, I would hate to find this. Not at all sure from reading
-- the code how it would work.

或者我最喜欢的,因为我喜欢 ANSI 92 连接语法:

SELECT R.[ID], C.[name] AS [company], X.Field
FROM [requests] AS R
INNER JOIN [eXample] as X ON X.[request_id] = R.ID
LEFT OUTER JOIN [companies] AS C ON R.[company_id] = S.ID
于 2009-07-03T18:28:11.220 回答
3

我想你想要:

SELECT R.[ID], ISNULL(C.[name], '') AS [company]
FROM [requests] AS R
    LEFT OUTER JOIN [companies] AS C
ON R.[company_id] = C.ID

编辑:见评论,需要左连接......

在我看来,也不需要左连接,因此您可以重写为:

SELECT R.[ID], C.[name] AS [company]
FROM [requests] AS R
    JOIN [companies] AS C
ON R.[company_id] = C.ID
于 2009-07-03T16:48:48.680 回答
1

以逗号更改表顺序使其在 sql server 2005,2008 和 2012 中工作

例如

假设您有一个如下查询,它将在 sql 2005 及更高版本中失败:

SELECT t1.*,t2.*, t3.*
FROM table1 AS t1, table2 as t2 
LEFT OUTER JOIN table3 AS t3
ON t1.id = t3.id
WHERE t1.id = t2.id

如果您重写查询并在联接之前更改逗号中的表顺序,则该查询将在 sql 2005 及更高版本中工作。例如

SELECT t1.*,t2.*, t3.*
FROM table2 as t2, table1 as t1 
LEFT OUTER JOIN table3 AS t3
ON t1.id = t3.id
WHERE t1.id = t2.id
于 2013-04-14T14:53:56.877 回答