MySQL 中的 OR 非空约束
在 MySQL 中创建非 NULL 约束以使 fieldA 和 fieldB 不能同时为 NULL 的最佳方法是什么? 我不在乎其中一个字段本身是否为 NULL,只要另一个字段具有非 NULL 值即可。 如果它们都有非 NULL 值,那就更好了。
What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这不是直接回答您的问题,而是一些附加信息。
在处理多列并检查是否全部为空或其中一列不为空时,我通常使用 COALESCE() - 它简短、可读且易于维护(如果列表增长):
这可以在触发器中使用。
This isn't an answer directly to your question, but some additional information.
When dealing with multiple columns and checking if all are null or one is not null, I typically use
COALESCE()
- it's brief, readable and easily maintainable if the list grows:This can be used in your trigger.
@Sklivvz:使用 MySQL 5.0.51a 进行测试,我发现它解析 CHECK 约束,但不强制执行它。 我可以插入(NULL,NULL)而没有错误。 测试了 MyISAM 和 InnoDB。 随后使用 SHOW CREATE TABLE 显示 CHECK 约束不在表定义中,即使我定义表时没有给出错误。
这与 MySQL 手册 相匹配,其中显示:“CHECK子句已解析,但被所有存储引擎忽略。”
因此对于 MySQL,您必须使用触发器来强制执行此规则。 唯一的问题是 MySQL 触发器无法引发错误或中止 INSERT 操作。 在触发器中可以执行的导致错误的一件事是将 NOT NULL 列设置为 NULL。
在更新之前您还需要一个类似的触发器。
@Sklivvz: Testing with MySQL 5.0.51a, I find it parses a CHECK constraint, but does not enforce it. I can insert (NULL, NULL) with no error. Tested both MyISAM and InnoDB. Subsequently using SHOW CREATE TABLE shows that a CHECK constraint is not in the table definition, even though no error was given when I defined the table.
This matches the MySQL manual which says: "The CHECK clause is parsed but ignored by all storage engines."
So for MySQL, you would have to use a trigger to enforce this rule. The only problem is that MySQL triggers have no way of raising an error or aborting an INSERT operation. One thing you can do in the trigger to cause an error is to set a NOT NULL column to NULL.
You also need a similar trigger BEFORE UPDATE.
MySQL 5.5引入了SIGNAL,所以我们不需要额外的Bill Karwin 的回答中不再有专栏。 比尔指出您还需要一个更新触发器,因此我也将其包含在内。
MySQL 5.5 introduced SIGNAL, so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too.
这是此类约束的标准语法,但 MySQL 之后会很高兴地忽略该约束
This is the standard syntax for such a constraint, but MySQL blissfully ignores the constraint afterwards
我在 SQL Server 中做了类似的事情,我不确定它是否可以直接在 MySQL 中工作,但是:
至少我相信这是语法。
但是,请记住,您无法跨表创建检查约束,只能检查一张表中的列。
I've done something similar in SQL Server, I'm not sure if it will work directly in MySQL, but:
At least I believe that's the syntax.
However, keep in mind that you cannot create check constraints across tables, you can only check the columns within one table.
使用 GENERATED ALWAYS 列和 COALESCE ... NOT NULL: 完成了此操作
我在 MySQL 版本 8.0.22 上
I accomplished this using a GENERATED ALWAYS column with COALESCE ... NOT NULL:
on MySQL version 8.0.22