我需要将MySQL表中的行数限制为仅限10。我只需要从MySQL实现这一点,即不使用任何编程语言。
我创建了一个实现 MAX_ROWS = 10
的表,但它无效。
请查看这些屏幕截图。
我很困惑如何做到这一点。如果有人会为我提供解决方案,那对我来说真的很有帮助。
感谢。
答案 0 :(得分:2)
我认为MySQL没有提供这样的内置功能。一种解决方案是您可以创建触发器。
CREATE TRIGGER your_trigger_name
BEFORE INSERT ON your_table_name
FOR EACH ROW
BEGIN
DECLARE cnt INT;
SELECT count(*) INTO cnt FROM your_table_name;
IF cnt = 10 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'You can store only 10 records.';
END IF;
END;
在桌面上尝试以上触发器。将table_name替换为 your_table_name 。
希望这会对你有所帮助。
答案 1 :(得分:0)
因为检查约束似乎不适用于MySql。您可以尝试在表上创建BEFORE INSERT TRIGGER
,并为某些不可为空的列设置NEW.column
值为NULL
以中断插入语句。
Ex:
CREATE TABLE mytable (
id INT NOT NULL,
col1 VARCHAR(255) NOT NULL,
col2 VARCHAR(255),
);
DELIMITER $$
CREATE TRIGGER mytable_before_trig BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
IF (SELECT COUNT(id) FROM mytable) > 3 THEN
SET NEW.id = NULL;
END IF;
END;
$$
现在尝试在mytable中插入记录,它会通过抛出错误来忽略第4条记录。
答案 2 :(得分:0)
这是一个想法......:
CREATE TABLE my_table
(id int auto_increment PRIMARY KEY
,val char(1) NOT NULL
);
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 1 row affected (0.02 sec)
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
INSERT INTO my_table (val) SELECT 'b' FROM (SELECT 1) x WHERE (SELECT COUNT(*) FROM my_table) < 5;
Query OK, 0 rows affected (0.00 sec)
SELECT * FROM my_table;
+----+-----+
| id | val |
+----+-----+
| 1 | b |
| 2 | b |
| 3 | b |
| 4 | b |
| 5 | b |
+----+-----+