【问题标题】:SQL hide result if all three fields are 'Yes'如果三个字段都为“是”,则 SQL 隐藏结果
【发布时间】:2013-01-14 02:15:39
【问题描述】:

我有一个包含 4 个字段的 MySQL 数据库:

id | planchanged | dataremoved | rolloverenabled |
1  | Yes         | Yes         | Yes             |
2  | NULL        |             |                 |
3  |             | Yes         |                 |
4  | Yes         |             | Yes             |
5  |             |             | NULL            |

我如何查询此数据库以仅显示在这三个字段上没有全部“是”的记录。另请注意,某些字段可能为 Null。因此,基于该示例,我的结果应显示记录 2、3、4 和 5。

【问题讨论】:

  • “还请考虑到某些字段可能为空” --- 看起来像一个职位描述。您是否尝试过自己解决任务?
  • 是的,我做到了,但我只能得到结果以显示所有三个都是空白并且任何 Null 记录都没有出现。不知道你说的职位描述是什么意思。
  • 只是为了好玩 - 不需要考虑 NULL 行为的最直接条件是:NOT (planchanged = 'Yes' AND dataremoved = 'Yes' AND rolloverenabled = 'Yes')

标签: php mysql


【解决方案1】:
SELECT * 
FROM yourTableName 
WHERE planchanged IS NULL OR planchanged <> 'Yes' 
OR dataremoved IS NULL OR dataremoved <> 'Yes' 
OR rolloverenabled IS NULL OR rolloverenabled <> 'Yes'

SQL Fiddle

【讨论】:

  • 这些不是多余的吗:planchanged IS NULL OR planchanged 'Yes'
  • @Boundless: NULL 从不匹配任何东西。所以NULL = 'Yes' == false,NULL &lt;&gt; 'Yes' == false
  • @Boundless 不幸的是,不适用于 mysql(以及大多数其他取决于 NULL 匹配设置)。见sqlfiddle.com/#!2/2fdf4/3
  • 谢谢你的回复和所有的cmets我当然学到了一些关于NULL的新东西
【解决方案2】:

你可以这样做

SELECT * FROM TableName 
WHERE coalesce(planchanged,'-') <> 'Yes' OR 
coalesce(dataremoved,'-') <> 'Yes' OR
coalesce(rolloverenabled,'-') <>'Yes'

SQLFIDDLE DEMO

【讨论】:

  • 如果 2 列是,第三列不是,他希望它显示
  • 只需将AND 替换为OR
  • 请注意,在 where 子句中使用 coalesce 将停止在这些列上使用任何索引
  • @lc。谢谢,我没有意识到这一点。在这种情况下,您的答案应该适用于 OP。我会保留我的答案。
【解决方案3】:
SELECT * 
FROM  yourTableName 
WHERE planchanged IS NULL 
  OR  dataremoved IS NULL 
  OR  rolloverenabled IS NULL 
  OR  planchanged <> 'Yes' 
  OR  dataremoved <> 'Yes' 
  OR  rolloverenabled <> 'Yes'

【讨论】:

  • "..仅显示不包含所有“是”的记录..." 那些 OR 不应该是 AND 吗?
  • 不,他们不应该。查询是正确的。请阅读问题。
  • 太好了,我在查询中添加了空检查。我不知道'是' NULL 是假的
  • 是的,因为null 不等于任何东西。见stackoverflow.com/questions/1833949/…
  • 有趣的是它不等于任何东西,但它也不等于。
猜你喜欢
  • 2013-10-02
  • 2021-07-10
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多