我在从sql查询中获取结果时遇到问题。我需要两个where子句的结果。我使用SQLServer2014
表1:产品
ProductID
1
2
3
4
5
表2:供应商
SupplierID
1
2
3
表3:Product_Supplier
ProductSupplierID|ProductID|SupplierID|Reference
1 |1 |1 |Ref001
2 |1 |2 |Ref002
3 |2 |1 |Ref003
4 |3 |2 |Ref004
5 |4 |2 |Ref005
我想要的结果是当我设置时:
其中(ProductID <4)和(SupplierID = 2)
我必须得到结果:ProductID 4下与SupplierID 2相关的所有产品,如果Product_Supplier中不存在此产品,则我必须获得Reference = Null
ProductID|SupplierID|Reference
1 |2 |Ref002
2 |2 |Null
3 |2 |Ref004
我启动了一些sql脚本,但无法获得正确的结果
select a.ProductID, b.SupplierID, C.Reference from Product as a
left outer join Product_Supplier as c on c.ProductID= a.ProductID
left outer join Supplier as B on b.SupplierID = c.SupplierID
where a.ProductID<4 and b.SupplierID=2
Felix Pamittan的回答:
SELECT
t.*,
ps.Reference
FROM (
SELECT *
FROM Product
CROSS JOIN Supplier
WHERE
ProductID < t.ProductID
AND SupplierID = t.SupplierID
) t
LEFT JOIN Product_Supplier ps
ON ps.ProductID = t.ProductID
AND ps.SupplierID = t.SupplierID
在此脚本上,我无法注入添加运行时的where代码。当我可以在sql的末尾设置where时,最终用户可以注入where参数。
SELECT
t.*,
ps.Reference
FROM (
SELECT *
FROM Product
CROSS JOIN Supplier
--WHERE
-- ProductID < t.ProductID
-- AND SupplierID = t.SupplierID
) t
LEFT JOIN Product_Supplier ps
ON ps.ProductID = t.ProductID
AND ps.SupplierID = t.SupplierID
where t.ProductID < 4
and t.SupplierID=2
我将在实际数据库中最后测试一次。
您需要首先获取Product
s和Supplier
s的所有组合。通过执行此操作CROSS JOIN
。最后,LEFT JOIN
在Product_Supplier
桌子上做一个:
SELECT
t.*,
ps.Reference
FROM (
SELECT *
FROM #Product
CROSS JOIN #Supplier
WHERE
ProductID < 4
AND SupplieIrD = 2
) t
LEFT JOIN #Product_Supplier ps
ON ps.ProductID = t.ProductID
AND ps.SupplierID = t.SupplieIrD
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句