如何处理没有结果的子查询?

时间:2019-05-23 14:02:09

标签: sql-server

我正在尝试在WHERE条件下使用子查询来构建查询,并且当子查询表为空时,我实际上想对查询不应用任何过滤器,并获取所有条目。

我如何实现自己想要的?

这是我的查询

<ImageView
        app:layout_constraintLeft_toRightOf="@+id/label_text_view"
        app:layout_constraintStart_toEndOf="@+id/label_text_view"
        app:layout_constraintTop_toTopOf="parent"

如果我没有喜欢的植物,我想要所有植物!

3 个答案:

答案 0 :(得分:2)

您可以添加第二个条件来处理这种情况:

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)

答案 1 :(得分:0)

您可以使用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

答案 2 :(得分:0)

我没有足够的声誉来发表评论,但这可能有用

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