sql - Sql-Server 中的父子关系问题

标签 sql sql-server tsql parent-child

假设我在sql server中有两个具有父子关系的,如下所示,

父表:

Parentid  value 

1         demo
2         demo2

子表:

childid     parchildid   subvalue

1           1            demo1
2           1            demo2

此处子表中的parchildid是引用父表parentid外键/.

我需要检索特定parentid 的子表数据。所以,我使用了下面的查询

 select *from child
 where parchildid in (select parchildid from parent)

它给出了以下输出。 (子表的所有行)

 childid    parchildid   subvalue

  1         1            demo1
  2         1            demo2

但如您所见,我在子查询中给出了一个 invalid 列 (parchildid)(parchildid 属于 子表而不是父表)。

我想知道为什么 sql server 没有抛出任何错误。

正在运行从父级中选择 parchildid 单独查询会出现无效列错误。

谁能解释一下为什么子查询中没有抛出错误?那里的逻辑是如何运作的?

谢谢

最佳答案

来自MSDN :

If a column does not exist in the table referenced in the FROM clause of a subquery, it is implicitly qualified by the table referenced in the FROM clause of the outer query.

在您的情况下,由于 parchildid 是外部查询中表中的一列,因此没有错误。然而,查询本身无法找到这样的列,因此失败。

关于sql - Sql-Server 中的父子关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339768/

相关文章:

php - 关系划分SQL

c# - SELECT 似乎阻止了 UPDATE 语句

sql-server - 在 SQL Server 中插入后获取 ID

sql - 远离 SQL 注入(inject)

sql - 如何在事务之间的postgresql中保存表进度?

sql-server - 使用 2FA AD 组登录用户(DB_Owner 帐户)登录的 Azure 不允许创建架构,而普通 AD/LAN 登录用户可以创建架构

sql - SQL Server 2008中使用Date函数进行计算

.net - 识别并删除会破坏 FOR XML 的字符

sql - 'sp_executesql' 附近的语法不正确

sql - 如果记录作为外部表存在于另一个表中,如何不删除?