我有两个表ItemsDetails和ItemsSquare
**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表中我想显示ItemDetails表中的所有记录以及来自ItemsSquare表的记录,该表具有与ItemDetails相同的ItmDtlId,然后将ItemDetails表和Itemsquare表中的Quantity作为Qty> ItmSqQty进行比较
基本上我想从ItemDetails表中基于o ItmDtId访问ItemsSquare表的列,因为第一个表与第二个表没有关系
我使用sql Correlated子查询如下,但我没有得到预期的结果
这是我的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
)