我在PhpMyAdmin中使用MySQL。我正在寻找一种方法来对表格施加约束,以便:
column1(int) + column2(int) + column3(int) <= 100
答案 0 :(得分:1)
到目前为止,在mysql中你不能在表定义中有这样的约束。您可以使用应用程序层来验证这一点。如果你想使用mysql,那么你可以使用signal
使用触发器并引发错误
https://dev.mysql.com/doc/refman/5.5/en/signal.html
触发器的外观如下
delimiter //
create trigger check_col_sum before insert on test
for each row
begin
if (new.column1+new.column2+new.column3) > 100 then
signal sqlstate '45000' set message_text = 'Sum of column1,column2 and column3 must be less than equal to 100';
end if;
end;//
delimiter ;
测试用例
mysql> create table test (id int auto_increment primary key, column1 int, column2 int, column3 int);
Query OK, 0 rows affected (0.14 sec)
mysql> delimiter //
mysql> create trigger check_col_sum before insert on test
-> for each row
-> begin
-> if (new.column1+new.column2+new.column3) > 100 then
-> signal sqlstate '45000' set message_text = 'Sum of column1,column2 and column3 must be less than equal to 100';
-> end if;
-> end;//
Query OK, 0 rows affected (0.09 sec)
mysql>
mysql> delimiter ;
mysql> insert into test (column1,column2,column3) values (10,20,30);
Query OK, 1 row affected (0.08 sec)
mysql> select * from test ;
+----+---------+---------+---------+
| id | column1 | column2 | column3 |
+----+---------+---------+---------+
| 1 | 10 | 20 | 30 |
+----+---------+---------+---------+
1 row in set (0.00 sec)
mysql> insert into test (column1,column2,column3) values (10,20,80);
ERROR 1644 (45000): Sum of column1,column2 and column3 must be less than equal to 100
mysql> select * from test ;
+----+---------+---------+---------+
| id | column1 | column2 | column3 |
+----+---------+---------+---------+
| 1 | 10 | 20 | 30 |
+----+---------+---------+---------+
1 row in set (0.00 sec)
答案 1 :(得分:0)
您可以使用MySQL5.7的新功能生成列,您可以在创建表时在第三列中定义两列的总和,或者可以通过 ALTER <添加列/ strong>命令。实施例
CREATE TABLE triangle(
sidea DOUBLE,
sideb DOUBLE,
sidec DOUBLE AS (SQRT(sidea * sidea + sideb * sideb))
);
参考链接: