【问题标题】:How to set WHERE conditions if the IF() function returns FALSE and END query if it returns TRUE in mysql如果IF()函数返回FALSE,如何设置WHERE条件,如果在mysql中返回TRUE,则END查询
【发布时间】:2018-08-16 07:40:53
【问题描述】:

我想使用 mysql 来检查 MySQL 数据库中是否存在某个值。如果该值存在,我什么也不想做(我不想获取任何数据)。如果它不存在,那么我想设置一些where 条件。

所以这就是我目前所拥有的,但它不正确。因为我仍然获取数据,如果没有设置where condition

SELECT *,
CASE
WHEN ( table_name.record = 'inputrecord')
THEN
    //Do nothing because it is found already
ELSE 
    // since inputrecord does not exist, we will start looking for 'id'
    ( WHERE table_name.id = '123')
END                 
FROM table_name

注意:在上面的例子中,我写了WHEN ( table_name.record = 'inputrecord') 而不是 WHEN ( table_name.record != 'inputrecord')。这是因为我只想在数据不在表中时才继续查询。

也许将IF functionEXISTS function 一起使用会更好,但我不知道该怎么做。

任何帮助都会很棒。现在我收到错误

【问题讨论】:

  • 你愿意示范一下吗?
  • 如果您在 WHEN (table_name.record = 'inputrecord') 时什么都不做,那么为什么不尝试像“select * from table_name where table_name.record != 'inputrecord' and table_name .id = '123'"
  • @Dr M 能否请您重新阅读该问题。我在笔记中提到了为什么我不能这样做..

标签: php mysql


【解决方案1】:

这不是 SQL 的工作方式。

SQL 总是返回一组行。它可能为空,有时行可能包含 NULL。您必须确定过滤集合的条件。

一个通用示例:假设我们有一个包含列(型号、颜色、年份)的汽车表,而您想在表中查找有关汽车的信息:

(* Find all red cars *)
select * from cars where color = 'red'

(* Find all red cars from 1985 *)
select * from cars where color = 'red' and year = 1985

(* Find all colors which exist both in 1990 and 2000 *)
select distinct color from cars A where year=1990 and exists (select 1 from cars B where year=2000 and B.color = A.color) 

请准确说出你想要达到的目标

编辑:应该这样做

(* select a record cars = 'Audi' only if cars = 'BMW' is not found in the whole table. otherwise. I do not want to select Audi even if it exists *)

select * from cars where model = 'Audi' and not exists (select 1 from cars where model = 'BMW')

这里,如果您的表中有宝马,您将获得 0 行,否则为奥迪列表

【讨论】:

  • 为了简单起见,我试图选择一个记录 cars = 'Audi' 只有当在整个表的记录中没有找到 cars = 'BMW' 时。除此以外。即使存在奥迪,我也不想选择它。
  • 非常感谢简单而详细的解释。真的很棒的想法:)
【解决方案2】:
 select * 
 from table_name 
 where case when table_name.record <> 'inputrecord' 
               then table_name.id = '123' 
               else 1=1 
       end 

你可以在你的代码中应用给定的条件

  1. 当输入条件不匹配时,应用您的过滤条件。

  2. 当输入条件匹配时(其他情况)然后检索您想要的结果。

【讨论】:

  • 谢谢让我试试这个:)
  • 谢谢,但我需要的是,如果在整个表中只找到一次 ` 'inputrecord' ,则条件应该返回 false 并且应该返回 0 行。但是,如果在任何时候都没有在表中找到“输入记录”,那么我想应用过滤器并返回行。你的解决方案几乎就在那里,但它会测试每一行的`'inputrecord'`。因此,如果它存在于前一行中,并且对另一行进行了另一次检查,它将忽略前一次检查并返回不同的结果。任何想法都可以很好地解决这个问题
【解决方案3】:

试试这个...

SELECT *
CASE
 WHEN table_name.record = 'inputrecord' THEN 'Unspecified'
 WHEN table_name.id = '123' THEN 'table by id'
END
FROM table_name;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多