如果在where语句中使用

问题描述 投票:1回答:3

我有4张桌子:

  1. Table_op_type
  2. Table_maintenancetype
  3. Table_repair_time
  4. Table_repair_type

[每个表都有一列可以是假的,而当我选择Table_maintenancereport时,我有一个Table_maintenancereport有很多列,而在Table_maintenancereport外键中有4列是从4向上的表给出的,而每个表中的一行是正确的代码可以正常工作,但是当从表返回多于一行时出现此错误。

子查询返回了多个值。当子查询遵循=,!=,,> =或将子查询用作表达式时,不允许这样做。

我该如何解决?

我的代码是:

SELECT *
FROM Table_maintenancereport
WHERE mtypeid IN (IIF(@smtype = 1, (SELECT Table_maintenancetype.id FROM Table_maintenancetype WHERE enable_search = 1), mtypeid))
  AND op_typeid IN (IIF(@sop IN (1), (SELECT Table_op_type.id FROM Table_op_type WHERE enable_search = 1), op_typeid))
  AND repaire_timeid IN (IIF(@stime IN (1), (SELECT Table_repair_time.id FROM Table_repair_time WHERE enable_search = 1), repaire_timeid))
  AND repaire_typeid IN (IIF(@stype = 1, (SELECT Table_repair_type.id FROM Table_repair_type WHERE enable_search = 1), repaire_typeid));
sql sql-server sql-server-2017
3个回答
1
投票

您需要修复where条件。您可以使用基本逻辑运算符执行此操作。无法通过iif()case()表达式返回集合。

所以:

WHERE (@smtype <> 1 OR
       mtypeid IN (SELECT Table_maintenancetype.id FROM Table_maintenancetype WHERE enable_search = 1)
      ) AND
      (@sop <> 1 OR
       op_typeid IN (SELECT Table_op_type.id FROM Table_op_type WHERE enable_search = 1)
      ) AND
      (@stime <> 1 OR
       repaire_timeid IN (SELECT Table_repair_time.id FROM Table_repair_time WHERE enable_search = 1)
      ) AND
      (@stype <> 1 OR
       repaire_typeid IN (SELECT Table_repair_type.id FROM Table_repair_type WHERE enable_search = 1)
      );

1
投票

如果我正在解释您要正确执行的操作:

SELECT *
FROM Table_maintenancereport mr
LEFT OUTER JOIN Table_maintenancetype mt ON mr.mtypeid = mt.id AND enable_search = 1
LEFT OUTER JOIN Table_op_type ot ON mr.op_typeid = ot.id AND enable_search = 1
LEFT OUTER JOIN Table_repair_time rt ON mr.repaire_timeid = rt.id AND enable_search = 1
LEFT OUTER JOIN Table_repair_type rty ON mr.repaire_typeid = rty.id AND enable_search = 1
WHERE (ISNULL(@smtype,-1) != 1 OR mt.id IS NOT NULL)
AND (ISNULL(@sop,-1) != 1 OR ot.id IS NOT NULL)
AND (ISNULL(@stime,-1) != 1 OR rt.id IS NOT NULL)
AND (ISNULL(@stype,-1) != 1 OR rty.id IS NOT NULL)

因此,对于每个@variable,如果将其设置为1,则相应的字段必须是可搜索的ID之一,才能显示在输出中。如果变量未设置为1,则不会过滤相应的字段。


0
投票

也许您可以在where子句中使用CASE WHEN语句,例如:

   select
    *
from
    Table_maintenancereport
where
    case
        when @smtype = 1 then mtypeid in (
            select Table_maintenancetype.id
        from
            Table_maintenancetype
        where
            enable_search = 1)
        else mtypeid = mtypeid end

    ....
© www.soinside.com 2019 - 2024. All rights reserved.