作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
请看下表结构:
CREATE TABLE Person (id int not null, PID INT NOT NULL, Name VARCHAR(50))
CREATE TABLE [Order] (OID INT NOT NULL, PID INT NOT NULL)
INSERT INTO Person VALUES (1,1,'Ian')
INSERT INTO Person VALUES (2,2,'Maria')
INSERT INTO [Order] values (1,1)
select * from Person WHERE id IN (SELECT ID FROM [Order])
最佳答案
这种行为虽然不直观,但在 Microsoft 的知识库中有很好的定义:
KB #298674 : PRB: Subquery Resolves Names of Column to Outer Tables
从那篇文章:
To illustrate the behavior, use the following two table structures and query:
CREATE TABLE X1 (ColA INT, ColB INT)
CREATE TABLE X2 (ColC INT, ColD INT)
SELECT ColA FROM X1 WHERE ColA IN (Select ColB FROM X2)
The query returns a result where the column ColB is considered from table X1.
By qualifying the column name, the error message occurs as illustrated by the following query:
SELECT ColA FROM X1 WHERE ColA in (Select X2.ColB FROM X2)
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'ColB'.
If you don't find column x in the current scope, traverse to the next outer scope, and so on, until you find a reference.
Order.PID
指向
Person.id
或
Person.PID
?设计您的表格,以便人们无需询问您就可以找出关系。 A
PersonID
应该总是
PersonID
,无论它在模式中的哪个位置;与
OrderID
相同.为完全模棱两可的模式节省几个输入字符并不是一个好的代价。
EXISTS
代替条款:
... FROM dbo.Person AS p WHERE EXISTS
(
SELECT 1 FROM dbo.[Order] AS o
WHERE o.PID = p.id -- or is it PID? See why it pays to be explicit?
);
关于SQL IN 查询产生奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18577622/
我是一名优秀的程序员,十分优秀!