[英]How to handle a subquery with no results?
我正在嘗試在WHERE條件下使用子查詢來構建查詢,並且當子查詢表為空時,我實際上不希望對我的查詢應用任何過濾器,並獲取所有條目。
我怎樣才能實現自己想要的?
這是我的查詢:
SELECT
m.Material,
p.Plant
FROM dbo.AllPlants AS p
JOIN dbo.AllMaterials AS m
ON p.MaterialID = m.MaterialID
WHERE p.Plant IN ( SELECT Plant FROM dbo.MyFavoritePlants);
如果我沒有喜歡的植物,我想要所有植物!
您可以添加第二個條件來處理這種情況:
SELECT
m.Material,
p.Plant
FROM dbo.AllPlants AS p
JOIN dbo.AllMaterials AS m
ON p.MaterialID = m.MaterialID
WHERE p.Plant IN (SELECT Plant FROM dbo.MyFavoritePlants)
OR NOT EXISTS (SELECT 1 FROM dbo.MyFavoritePlants)
可以使用LEFT JOIN
代替子查詢。 因此,如果MyFavoritePlants
表中沒有條目,它將忽略LEFT JOIN
條件。
SELECT m.Material,
p.Plant
FROM dbo.AllPlants AS p
JOIN dbo.AllMaterials AS m ON p.MaterialID = m.MaterialID
LEFT JOIN dbo.MyFavoritePlants FP ON FP.Plant = p.Plant
我沒有足夠的聲譽來發表評論,但這可能有用
SELECT
m.Material,
p.Plant
FROM dbo.AllPlants AS p
JOIN dbo.AllMaterials AS m ON p.MaterialID = m.MaterialID
LEFT JOIN dbo.MyFavoritePlants FP ON FP.Plant = P.Plant
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.