如何确保数据库表中只有一行?

发布于 2024-10-12 03:47:38 字数 250 浏览 2 评论 0原文

我想确保名为“myTable”的 MySQL 表只有一行。

所以我需要能够对此行进行更新,但显然插入和删除应该是不可能的。

我问这个问题是因为这个 堆栈溢出答案

谢谢!

I would like to ensure that my MySQL table named "myTable" has one-and-only-one row.

So I need to be able to do Update on this row but obviously Insert and Remove should be not possible.

I am asking this question because of this Stack Overflow answer

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

扶醉桌前 2024-10-19 03:47:38
CREATE TABLE `myTable` (
  `id` enum('1') NOT NULL,
  `MyValue1` int(6) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='The ENUM(''1'') construct as primary key is used to prevent that more than one row can be entered to the table';
CREATE TABLE `myTable` (
  `id` enum('1') NOT NULL,
  `MyValue1` int(6) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='The ENUM(''1'') construct as primary key is used to prevent that more than one row can be entered to the table';
慕巷 2024-10-19 03:47:38

给您的两个建议,其中一个或两个都可能有效,具体取决于您尝试存储的数据的具体情况:

和/或

Two suggestions for you, one or both which may work depending on the particulars of the data you're trying to store:

AND/OR

半仙 2024-10-19 03:47:38

最简单的方法是创建一个只有一个合法值的列,然后声明它not null unique

这会强制表的行数不超过,但仍允许零行。如果您需要防止删除唯一的行,请使用不同答案中给出的触发器方法。

create table example( 
    enforce_one_row enum('only') not null unique default 'only',
    ... your columns ....
);

The easiest approach is to create a column that only has one legal value, then to declare it not null unique.

This forces the table to have no more than one row, but still allows zero rows. If you need to prevent the removal of the only row, use the trigger approach given in a different answer.

create table example( 
    enforce_one_row enum('only') not null unique default 'only',
    ... your columns ....
);
划一舟意中人 2024-10-19 03:47:38

试试这个:

CREATE TABLE foo (x INT NOT NULL PRIMARY KEY CHECK (x = 1), col1 INT NOT NULL, col2 INT NOT NULL);

Try this:

CREATE TABLE foo (x INT NOT NULL PRIMARY KEY CHECK (x = 1), col1 INT NOT NULL, col2 INT NOT NULL);
弱骨蛰伏 2024-10-19 03:47:38

您可以使用表权限(假设一旦您设置了相关权限来阻止插入/删除,并且您不应该再更新权限,但是,任何拥有权限的用户都可以再次覆盖权限)

插入一加-首先只有一条记录
然后通过在 table_priv 列中禁用 INSERT、UPDATE、DROP 来添加权限

mysql> desc tables_priv;
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
| Field       | Type                                                                                                                    | Null | Key | Default           | Extra |
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
| Host        | char(60)                                                                                                                | NO   | PRI |                   |       |
| Db          | char(64)                                                                                                                | NO   | PRI |                   |       |
| User        | char(16)                                                                                                                | NO   | PRI |                   |       |
| Table_name  | char(64)                                                                                                                | NO   | PRI |                   |       |
| Grantor     | char(77)                                                                                                                | NO   | MUL |                   |       |
| Timestamp   | timestamp                                                                                                               | NO   |     | CURRENT_TIMESTAMP |       |
| Table_priv  | set('Select','Insert','Update','Delete','Create','Drop','Grant','References','Index','Alter','Create View','Show view') | NO   |     |                   |       |
| Column_priv | set('Select','Insert','Update','References')                                                                            | NO   |     |                   |       |
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
8 rows in set (0.00 sec)

You can make use on tables privileges (assuming once you have set the relevant privileges to block insert/delete, and you should not update the privileges anymore, however, any user has the privileges can override the privileges again)

insert the one-and-only-one record first
then add in the privileges by disable INSERT, UPDATE, DROP in column table_priv

mysql> desc tables_priv;
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
| Field       | Type                                                                                                                    | Null | Key | Default           | Extra |
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
| Host        | char(60)                                                                                                                | NO   | PRI |                   |       |
| Db          | char(64)                                                                                                                | NO   | PRI |                   |       |
| User        | char(16)                                                                                                                | NO   | PRI |                   |       |
| Table_name  | char(64)                                                                                                                | NO   | PRI |                   |       |
| Grantor     | char(77)                                                                                                                | NO   | MUL |                   |       |
| Timestamp   | timestamp                                                                                                               | NO   |     | CURRENT_TIMESTAMP |       |
| Table_priv  | set('Select','Insert','Update','Delete','Create','Drop','Grant','References','Index','Alter','Create View','Show view') | NO   |     |                   |       |
| Column_priv | set('Select','Insert','Update','References')                                                                            | NO   |     |                   |       |
+-------------+-------------------------------------------------------------------------------------------------------------------------+------+-----+-------------------+-------+
8 rows in set (0.00 sec)
屋顶上的小猫咪 2024-10-19 03:47:38

如果您的数据库设置为“严格”模式,您可以创建如下表:

create table foo(id enum('SYSROW') not null,(其他列定义)主键(id));

If your database is set to 'strict' mode, you can create a table like this one:

create table foo (id enum('SYSROW') not null, (other column definitions) primary key (id));

怪我入戏太深 2024-10-19 03:47:38
    create table if not exists myTable (
        ID int not null
    ) engine=innodb;

    select 'create trigger tbi_myTable';
    drop trigger if exists tbi_myTable;
    delimiter //
    create trigger tbi_myTable 
        before insert on myTable 
        for each row
    begin
        if (select count(1) from myTable) > 0 then
            -- Signal is only in 5.6 and above use another way to raise an error: if less than 5.6
            SIGNAL SQLSTATE '50000' SET MESSAGE_TEXT = 'Cannot insert into myTable only one row alowed!';
        end if;
    END //
    delimiter ;
    insert into myTable values (1);

    -- This will generate an error
    insert into myTable values (2);

    -- This will only have one row with "1"
    select * from myTable;
    create table if not exists myTable (
        ID int not null
    ) engine=innodb;

    select 'create trigger tbi_myTable';
    drop trigger if exists tbi_myTable;
    delimiter //
    create trigger tbi_myTable 
        before insert on myTable 
        for each row
    begin
        if (select count(1) from myTable) > 0 then
            -- Signal is only in 5.6 and above use another way to raise an error: if less than 5.6
            SIGNAL SQLSTATE '50000' SET MESSAGE_TEXT = 'Cannot insert into myTable only one row alowed!';
        end if;
    END //
    delimiter ;
    insert into myTable values (1);

    -- This will generate an error
    insert into myTable values (2);

    -- This will only have one row with "1"
    select * from myTable;
望她远 2024-10-19 03:47:38

您可以使用 IF 语句检查 mySQL。

IF (SELECT count(*) FROM myTable) = 1
    //your SQL code here.

You can check in mySQL using IF statement.

IF (SELECT count(*) FROM myTable) = 1
    //your SQL code here.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文