【问题标题】:mysql select column where condition 1 exists otherwise condition 2 but not bothmysql选择条件1存在的列,否则条件2但不是两者
【发布时间】:2015-12-12 15:28:15
【问题描述】:

我有一个像这样的简单表格:

id | com_id | sec_id | branch_id | code 
1      1         1        3        some_code_with_all_fields_notnull <<--- this one
2      2         3        3        some_code
3      3         2        6        some_code
4      1       NULL      NULL      some_code_with_some_fields_null <<--- or this one
5      2         3        9        some_code

现在,我只需要选择一条记录,如下所示:
如果没有提供 sec_id 或 branch_id 作为参数,我只需要选择相应列值为空的行。如果它们已作为参数提供,我只需要选择对应列值与每个参数值匹配的行。

我尝试了一个普通的 where 子句,如下所示: select code from comcodes where com_id = :com_id and (sec_id = :sec_id or sec_id is null) and (branch_id = :branch_id or branch_id is null)

但是 where 遍历所有行并返回匹配两个条件的所有行 这就是我不想要的。我希望它只返回满足第一个条件或第二个条件不满足的一行

我使用“OR null”部分的原因是,如果提供了 sec_id 或 branch_id 但没有找到与它们匹配的记录,我需要返回具有 null 值的行

你能帮我解决这个问题吗

【问题讨论】:

  • 请在您的问题中写下表格,不要粘贴它的图像,尤其是 ASCII 表格...

标签: mysql


【解决方案1】:

一种解决方案是添加一个 ORDER BY,然后添加一个 LIMIT 1:

select code
from comcodes
where
  com_id = :com_id and
  (sec_id = :sec_id or sec_id is null)
  and (branch_id = :branch_id or branch_id is null)
order by
  CASE WHEN (sec_id is not null) THEN 1 ELSE 2 END
LIMIT 1

这将优先考虑不为空的 sec_id(如果存在)。

【讨论】:

  • 感谢@fthiella,这仅对 sec_id 起作用,但我需要优先考虑任何其他字段,只要它不为空,而不仅仅是 sec_id
猜你喜欢
  • 2015-08-29
  • 2018-04-30
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
相关资源
最近更新 更多