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.
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What means in Dart static type and why it differs
- php PDO::FETCH_ASSOC doesnt detect select after ba
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.
@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.
This is the standard syntax for such a constraint, but MySQL blissfully ignores the constraint afterwards
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.
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.