gpt4 book ai didi

sql - 该列在IN子句中不存在,但是SQL运行

转载 作者:行者123 更新时间:2023-12-04 13:17:41 25 4
gpt4 key购买 nike

我有一个使用IN子句的查询。这是一个简化的版本:

SELECT *
FROM table A
JOIN table B
ON A.ID = B.ID
WHERE B.AnotherColumn IN (SELECT Column FROM tableC WHERE ID = 1)
tableC没有 Column列,但是查询执行得很好,没有错误消息。谁能解释为什么?

最佳答案

如果外部查询中的表具有该名称的列,则此方法有效。这是因为来自外部查询的列名可用于子查询,并且您可能故意在子查询SELECT列表中选择一个外部查询列。

例如:

CREATE TABLE #test_main (colA integer) 
CREATE TABLE #test_sub (colB integer)

-- Works, because colA is available to the sub-query from the outer query. However,
-- it's probably not what you intended to do:
SELECT * FROM #test_main WHERE colA IN (SELECT colA FROM #test_sub)

-- Doesn't work, because colC is nowhere in either query
SELECT * FROM #test_main WHERE colA IN (SELECT colC FROM #test_sub)

正如Damien所观察到的,保护自己免受这种不太明显的“陷阱”的最安全方法是养成在子查询中限定列名的习惯:
-- Doesn't work, because colA is not in table #test_sub, so at least you get
-- notified that what you were trying to do doesn't make sense.
SELECT * FROM #test_main WHERE colA IN (SELECT #test_sub.colA FROM #test_sub)

关于sql - 该列在IN子句中不存在,但是SQL运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5076906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com