简体   繁体   English

MySQL 表中的默认记录

[英]MySQL Default Record from Table

I use MySQL 5.6 and I have 3 tables.我使用 MySQL 5.6,我有 3 张桌子。 Two of them are a list of data, and the third table is used for a relationship between them.其中两个是数据列表,第三个表用于它们之间的关系。 In the third table I would like to identify a default record for each id1, so I added a column named predt to let me know which record is the default one.在第三个表中,我想为每个 id1 标识一条默认记录,所以我添加了一个名为 predt 的列,让我知道哪条记录是默认记录。 Something like this:像这样的东西:

id1 | id2 | predt
1   | 1   | 0
1   | 2   | 1
1   | 3   | 0

In this example I will know that the second row is the default one for id1 = 1.在此示例中,我将知道第二行是 id1 = 1 的默认行。

Whats worries me is that it's possible that more than one record could have the value 1 for column predt where id1 = 1.让我担心的是,对于 id1 = 1 的列 predt,可能有多个记录的值为 1。

I validate that this doesn't happen, is the first thing I do in the SP that inserts or updates a record in this table.我确认这不会发生,这是我在 SP 中插入或更新此表中的记录的第一件事。 But if someone updates the table directly there is no restriction in the table to stop it from doing so (like a foreign key restriction).但是,如果有人直接更新表,则表中没有任何限制可以阻止它这样做(如外键限制)。

create table table1 (
id int(10) not null auto_increment,
description varchar(100) not null,
primary key(id))
engine innodb,
default character set latin1;

create table table2 (
id int(10) not null auto_increment,
description varchar(100) not null,
primary key(id))
engine innodb,
default character set latin1;

create table table3 (
id1 int(10) not null,
id2 int(10) not null,
predt tinyint(1) not null default 0,
primary key(id1,id2))
engine innodb,
default character set latin1;

I always treated this case in the same way, and so far it has worked.我总是以同样的方式处理这个案例,到目前为止它已经奏效了。 But I would like to know if there is a better way to work with this kind of cases.但我想知道是否有更好的方法来处理这种情况。

You should test if for that particular row already exists such predt = 1 In higher mysql Versions you could use a CHECK Constraint with the same purpose您应该测试该特定行是否已经存在,例如 predt = 1 在更高的 mysql 版本中,您可以使用具有相同目的的 CHECK 约束

DELIMITER $$
CREATE TRIGGER before_insert_table3 
BEFORE INSERT
ON table3 FOR EACH ROW
BEGIN
    IF NEW.predt = 1 then    
    IF EXISTS(SELECT 1 FROM table3 WHERE predt = 1 AND id1 = NEW.id1) THEN
        SIGNAL SQLSTATE '45000'
            SET MESSAGE_TEXT = ' predt 1 already exist';
    END IF; 
END IF;
END $$

DELIMITER ;

DELIMITER $$
CREATE TRIGGER before_update_table3 
BEFORE UPDATE
ON table3 FOR EACH ROW
BEGIN
    IF NEW.predt = 1 then    
        IF EXISTS(SELECT 1 FROM table3 WHERE predt = 1 AND id1 = NEW.id1) THEN
            SIGNAL SQLSTATE '45000'
                SET MESSAGE_TEXT = ' predt 1 already exist';
        END IF; 
    END IF;
END $$

DELIMITER ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM