SQL子查询返回了1个以上的结果

时间:2019-02-08 13:28:26

标签: sql sql-server tsql

我有一个查询,当我检查过滤器是否为NULL时,我将选择全部,但如果它们不为空,则仅选择具有那些过滤器的对象。查询如下。

SELECT * 
FROM [PointOfInterest]
WHERE [PointOfInterest].[Id] IN (CASE
                                    WHEN @filters IS NULL THEN [PointOfInterest].[Id]
                                    WHEN @filters IS NOT NULL THEN (SELECT DISTINCT [PointOfInterestIcon].[PointOfInterestId]
                                            FROM  [PointOfInterestIcon]
                                            WHERE [IconId] IN (SELECT [Id] FROM OPENJSON(@filters)WITH([Id] NVARCHAR(255))))
                                    END)

如果我删除CASE语句并仅将SELECT放入IN,则查询有效。有任何解决方法的想法吗?

2 个答案:

答案 0 :(得分:5)

只需使用常规布尔逻辑:

SELECT * 
FROM [PointOfInterest]
WHERE @filters IS NULL OR
      [PointOfInterest].[Id] IN (SELECT poi.[PointOfInterestId]
                                 FROM [PointOfInterestIcon] poi
                                 WHERE poiIconId IN (SELECT [Id] FROM OPENJSON(@filters) WITH ([Id] NVARCHAR(255)))
                                );

答案 1 :(得分:1)

您有一个内部选择,返回的内容多于一行。.您会用TOP 1限制该结果

SELECT * 
FROM [PointOfInterest]
WHERE [PointOfInterest].[Id] IN (
    CASE
            WHEN @filters IS NULL THEN [PointOfInterest].[Id]
            WHEN @filters IS NOT NULL THEN (
                    SELECT TOP 1 DISTINCT [PointOfInterestIcon].[PointOfInterestId]
                    FROM  [PointOfInterestIcon]
                    WHERE [IconId] IN (
                    SELECT [Id] FROM OPENJSON(@filters)WITH([Id] NVARCHAR(255))))
    END)