简体   繁体   English

SQL查询和错误子查询返回了多个值

[英]SQL query and error Subquery returned more than 1 value

Hello here is my SQL query : 您好,这是我的SQL查询:

WHERE table1.Regnumber IN (
    CASE 
        WHEN @fRegNumber IS NOT NULL AND @fRegNumber<>-1 THEN @fRegNumber
        ELSE (SELECT Regnumber FROM table2)
    END
)

An error: 一个错误:

'Subquery returned more than 1 value. '子查询返回的值超过1。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.' 当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,这是不允许的。

How can I fix this? 我怎样才能解决这个问题?

Change to: 改成:

WHERE IF(@fRegNumber IS NOT NULL AND @fRegNumber<>-1,
         table1.Regnumber = @fRegnumber),
         table1.Regnumber IN (SELECT Regnumber FROM table2))

WHERE x IN can be used in two ways: WHERE x IN可以通过两种方式使用:

WHERE x IN (expr1, expr2, expr3, ...)

In this case, if you use a subquery as the expression, it must return just a single value. 在这种情况下,如果将子查询用作表达式,则它必须仅返回单个值。 A subquery that returns multiple values will not be spliced in. 返回多个值的子查询将不会被拼接。

or: 要么:

WHERE x IN (subquery)

This is the format that allows a subquery to return multiple rows, and x will be tested against all of them. 这种格式允许子查询返回多行,并且x将针对所有行进行测试。

Since you want to conditionalize whether to test against a single value or the results of a subquery, you must do that outside the IN clause, using IF . 由于要确定是否要对单个值还是对子查询的结果进行测试,因此必须使用IFIN子句之外进行测试。

There may be other ways to write this query as a LEFT JOIN. 可能还有其他方式可以将此查询编写为LEFT JOIN。

The problem is with this subquery. 问题出在这个子查询上。

(SELECT Regnumber FROM table2)

It's returning every regnumber from the table. 它从表中返回每个regnumber。 In the context of the overall query, you have to pick just one. 在整个查询的上下文中,您只需选择一个即可。 The first step in solving your problem is to decide which one you want and why. 解决问题的第一步是确定您想要哪个,为什么。

I can see 2 approaches here. 我可以在这里看到2种方法。 One keeping the CASE statement this way: 一个这样保存CASE语句的人:

WHERE
    CASE    WHEN    COALESCE(@fRegNumber, -1) == -1
            THEN    t1.regnumber IN (SELECT t2.regnumber FROM table2))
            ELSE    t1.regnumber = @fRegNumber
    END

And the other one rephrasing the whole CASE statement into the appropriate logical operators: 另一个将整个CASE语句改写为适当的逻辑运算符:

WHERE
  (COALESCE(@fRegNumber, -1) != -1 AND t1.regnumber = @fRegNumber) OR
  (COALESCE(@fRegNumber, -1) == -1 AND t1.regnumber IN (SELECT t2.regnumber FROM table2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM