我是新来的,所以如果我做了违反惯例的事情,请告诉我。
在尝试更大更复杂的查询之前,我正在尝试创建一个包含单个外部联接的简单查询。当我在添加连接之前运行我的查询时,它按预期工作。当我添加连接时,查询返回错误消息。我无法确定错误的原因。我在Microsoft SQL Server 2008 R2中工作。
此查询成功运行并产生预期结果:
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1,
table2
where table1.id_num = table2.id_num
此查询无法成功运行:
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1,
table2
where table1 left outer join table2 on table1.id_num = table2.id_num
我得到的错误信息是:
Msg 4145, Level 15, State 1, Line 6
An expression of non-boolean type specified in a context where a condition is expected, near 'left'.
我也试过“外连接”而不是“左外连接”,但是这产生了类似的错误信息(唯一的区别是“靠近'外部'”而不是“靠近'左边'”。
我知道布尔意味着什么,但我不确定为什么这是一个问题。布尔运算符稍后出现在同一行中。我的代码看起来像我看到的其他代码一样。任何帮助将不胜感激。
答案 0 :(得分:1)
你的联接需要在FROM不在WHERE子句
之后use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1
left outer join table2 on table1.id_num = table2.id_num
答案 1 :(得分:1)
您正在使用不推荐使用的语法,列出表并在WHERE
子句中定义它们之间的关系已被显式JOIN
语句替换
FROM Table1 t1
JOIN Table2 t2
ON t1.col1 = t2.col1
LEFT JOIN Table3 t3
ON t1.col2 = t3.col1
旧样式连接允许外部连接:
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1,table2
where table1.id_num *= table2.id_num
应该避免使用这种旧语法,但如果遇到它们,有助于了解它们是什么。