SQL相关子查询怎么写

how to write SQL Correlated subqueries

我有两个 table ItemsDetailsItemsSquare

**ItemsDetails** table have following column

ItmDtlId P.K

Itmid F.K

AssetId F.k

Qty 

TDate

Approved

**ItemsSquare** table have following column

ItmSqrId P.k

ItmDtlId F.k

ItmSqQty

Date

来自 ItemsDetails table 我想显示来自 ItemDetails 的所有记录 table 也来自 ItemsSquare table 有 ItmDtlId 与 ItemDetails 中的相同,然后比较 ItemDetails table 和 Itemsquare table 中的数量作为 Qty > ItmSqQty

基本上我想从 ItemDetails table 基于 o ItmDtId 访问 ItemsSquare table 的列 因为第一个 table 与第二个 table

没有关系

我正在使用 sql 相关子查询如下,但我没有得到预期的结果

这是我的sql查询

SELECT itd.ItmDtlId
     , it.Itmid
     , itd.Qty
     , itd.Approved
     , as.Assetid
     , as.Assetname
     , itd.TDate 
  from ItemsDetails itd
  join Item it 
    on itd.Itmid = it.Itmid
  join Assets as 
    on itd.Assetsid = as.Assetsid
 WHERE itd.Approved = 1 
   and itd.ItmDtlId = (SELECT itd.ItmDtlId FROM ItemsSquare its WHERE itd.ItmDtlId = its.ItmDtlIdand itd.Qty > ItmSqQty) 

请建议我如何有效地编写 Sql 子查询以获得所需的结果

您是否可能错误地引用了子查询?

而不是:

...
AND itd.ItmDtlId = (
    SELECT itd.ItmDtlId 
    FROM ItemsSquare its
    WHERE itd.ItmDtlId = its.ItmDtlIdand
      AND itd.Qty > its.ItmSqQty
)

收件人:

...
AND itd.ItmDtlId = (
    SELECT its.ItmDtlId 
    FROM ItemsSquare its
    WHERE itd.ItmDtlId = its.ItmDtlIdand
      AND itd.Qty > its.ItmSqQty
)