Ошибка 3813 mysql

I’m trying to add a constraint on 2 columns in MySQL and I’m getting the following error:

lError Code: 3813. Column check constraint ‘offer_chk_1’ references
other column.

Is what I’m trying to do possible?

create table offer(
  offer_id int UNSIGNED NOT NULL AUTO_INCREMENT, 
  buyer_id int UNSIGNED not null, 
  seller_id int UNSIGNED not null check(buyer_id <> seller - id), 
  sell_ID int unsigned not null, 
  offer_date char(10) not null, 
  offering varchar(100) not null, 
  trade_offer boolean default false, 
  purchase_offer boolean default false, 
  primary key(offer_id), 
  foreign key(buyer_id) references customer(account_id) on update cascade on delete cascade, 
  foreign key(seller_id) references customer(account_id) on update cascade on delete cascade, 
  foreign key(sell_id) references sell(sell_id) on update cascade on delete cascade, 
  );

Sebin Benjamin's user avatar

asked Nov 3, 2019 at 15:51

3

It is possible but :

Foreign key referential actions (ON UPDATE, ON DELETE) are prohibited
on columns used in CHECK constraints. Likewise, CHECK constraints are
prohibited on columns used in foreign key referential actions.

that I found here :

https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html

And the way to do it if there is no FK on the columns:

CREATE TABLE parts (
    part_no VARCHAR(18) PRIMARY KEY,
    description VARCHAR(40),
    cost DECIMAL(10,2 ) NOT NULL CHECK (cost >= 0),
    price DECIMAL(10,2) NOT NULL CHECK (price >= 0),
    CONSTRAINT parts_chk_price_gt_cost 
        CHECK(price >= cost)
);

That I found here:

http://www.mysqltutorial.org/mysql-check-constraint/

answered Nov 3, 2019 at 16:10

VBoka's user avatar

VBokaVBoka

9,0053 gold badges16 silver badges24 bronze badges

I am attempting to create my first database in MySQL and running into a bit of a problem, when attepting to run the following table, I am getting the following error:

Error Code 3813: Column check constraint ‘section_ck_1’ references other column.

Here is the table I am trying to write

create table section (
course_id varchar(8),
sec_id varchar(8),
semester varchar(6) check (semester in (`Fall`, `Winter`, `Spring`, `Summer`)),
year numeric(4,0) check (year > 1701 and year < 2100),
building varchar(15),
room_number varchar(7),
time_slot_id varchar(4),
primary key (course_id, sec_id, semester, year),
foreign key(course_id) references course(course_id) on delete cascade,
foreign key (building, room_number) references classroom on delete set null);

I believe it is something incorrect with my ‘semester’ or ‘year’ rows, although I am not sure what the problem is, or how I would go about fixing it.

Error Code: 3813. Column check constraint ‘customer_details_chk_2’ references other column

CREATE TABLE Customer_Details
(
    Customer_Id int(4) auto_increment,
    C_FirstName char(20),
    C_LastName char(20),
    PRIMARY KEY (Customer_Id),
    C_Temperature decimal(5,2),
    Mail_Id char(20) unique not null,
    Customer_Ref_Number char(10) , CONSTRAINT CHECK_UC
    CHECK(BINARY Customer_Ref_Number = UPPER(Customer_Ref_Number)),
    Processing_Cost int check(Processing_Cost>500),
    Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)
);

Advertisement

Answer

MySQL only started supporting check constraints in MySQL 8.0.16 — released in April 2019.

Prior to that, the syntax was allowed (although perhaps with limitations), but nothing happened.

What is happening in your code is that you have:

Processing_Cost int check(Processing_Cost>500),
Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)

These are inline check constraints. That means they are part of the column definition. You can fix this just by adding commas:

Processing_Cost int,
check (Processing_Cost > 500),
Service_Charge numeric,
check (0.12*Processing_Cost >= Service_Charge)

I like to make my constraints obvious, so I would put them after the columns and give them names:

Processing_Cost int,
Service_Charge numeric,
constraint chk_customer_details_processing_cost check (Processing_Cost > 500),
constraint chk_customer_details_service_charge check (0.12*Processing_Cost >= Service_Charge)

Here is a db<>fiddle.

Note: Don’t use char() for column types — it pads the string with spaces. Use varchar().

Я пытаюсь создать свою первую базу данных в MySQL и столкнулся с небольшой проблемой, при попытке запустить следующую таблицу я получаю следующую ошибку:

Код ошибки 3813: ограничение проверки столбца section_ck_1 ссылается на другой столбец.

Вот таблица, которую я пытаюсь написать

create table section (
course_id varchar(8),
sec_id varchar(8),
semester varchar(6) check (semester in (`Fall`, `Winter`, `Spring`, `Summer`)),
year numeric(4,0) check (year > 1701 and year < 2100),
building varchar(15),
room_number varchar(7),
time_slot_id varchar(4),
primary key (course_id, sec_id, semester, year),
foreign key(course_id) references course(course_id) on delete cascade,
foreign key (building, room_number) references classroom on delete set null);

Я считаю, что что-то не так с моими строками «семестр» или «год», хотя я не уверен, в чем проблема и как бы я ее исправил.

1 ответ

semester varchar(6) check (semester in (`Fall`, `Winter`, `Spring`, `Summer`)),

Я думаю, вы хотели использовать одинарные кавычки для создания строковых литералов четырех сезонов. Должно получиться так:

semester varchar(6) check (semester in ('Fall', 'Winter', 'Spring', 'Summer')),

Строковые литералы заключаются в одинарные кавычки.

Обратные кавычки используются для разделения идентификаторов, таких как имена таблиц и имена столбцов. Использование обратных кавычек так, как вы сделали, казалось, будто вы намеревались semester иметь то же значение, что и один из четырех других столбцов с именами Fall, Winter, Spring , Summer.


1

Bill Karwin
10 Фев 2020 в 07:39

I’m trying to add a constraint on 2 columns in MySQL and I’m getting the following error:

lError Code: 3813. Column check constraint ‘offer_chk_1’ references
other column.

Is what I’m trying to do possible?

create table offer(
  offer_id int UNSIGNED NOT NULL AUTO_INCREMENT, 
  buyer_id int UNSIGNED not null, 
  seller_id int UNSIGNED not null check(buyer_id <> seller - id), 
  sell_ID int unsigned not null, 
  offer_date char(10) not null, 
  offering varchar(100) not null, 
  trade_offer boolean default false, 
  purchase_offer boolean default false, 
  primary key(offer_id), 
  foreign key(buyer_id) references customer(account_id) on update cascade on delete cascade, 
  foreign key(seller_id) references customer(account_id) on update cascade on delete cascade, 
  foreign key(sell_id) references sell(sell_id) on update cascade on delete cascade, 
  );

MySQL only started supporting check constraints in MySQL 8.0.16 — released in April 2019.

Prior to that, the syntax was allowed (although perhaps with limitations), but nothing happened.

What is happening in your code is that you have:

Processing_Cost int check(Processing_Cost>500),
Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)

These are inline check constraints. That means they are part of the column definition. You can fix this just by adding commas:

Processing_Cost int,
check (Processing_Cost > 500),
Service_Charge numeric,
check (0.12*Processing_Cost >= Service_Charge)

I like to make my constraints obvious, so I would put them after the columns and give them names:

Processing_Cost int,
Service_Charge numeric,
constraint chk_customer_details_processing_cost check (Processing_Cost > 500),
constraint chk_customer_details_service_charge check (0.12*Processing_Cost >= Service_Charge)

Here is a db<>fiddle.

Note: Don’t use char() for column types — it pads the string with spaces. Use varchar().

Error Code: 3813. Column check constraint ‘customer_details_chk_2’ references other column

CREATE TABLE Customer_Details
(
    Customer_Id int(4) auto_increment,
    C_FirstName char(20),
    C_LastName char(20),
    PRIMARY KEY (Customer_Id),
    C_Temperature decimal(5,2),
    Mail_Id char(20) unique not null,
    Customer_Ref_Number char(10) , CONSTRAINT CHECK_UC
    CHECK(BINARY Customer_Ref_Number = UPPER(Customer_Ref_Number)),
    Processing_Cost int check(Processing_Cost>500),
    Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)
);

Advertisement

Answer

MySQL only started supporting check constraints in MySQL 8.0.16 — released in April 2019.

Prior to that, the syntax was allowed (although perhaps with limitations), but nothing happened.

What is happening in your code is that you have:

Processing_Cost int check(Processing_Cost>500),
Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)

These are inline check constraints. That means they are part of the column definition. You can fix this just by adding commas:

Processing_Cost int,
check (Processing_Cost > 500),
Service_Charge numeric,
check (0.12*Processing_Cost >= Service_Charge)

I like to make my constraints obvious, so I would put them after the columns and give them names:

Processing_Cost int,
Service_Charge numeric,
constraint chk_customer_details_processing_cost check (Processing_Cost > 500),
constraint chk_customer_details_service_charge check (0.12*Processing_Cost >= Service_Charge)

Here is a db<>fiddle.

Note: Don’t use char() for column types — it pads the string with spaces. Use varchar().

#mysql #sql

#mysql #sql

Вопрос:

 CREATE TABLE Customer_Details
(
    Customer_Id int(4) auto_increment,
    C_FirstName char(20),
    C_LastName char(20),
    PRIMARY KEY (Customer_Id),
    C_Temperature decimal(5,2),
    Mail_Id char(20) unique not null,
    Customer_Ref_Number char(10) , CONSTRAINT CHECK_UC
    CHECK(BINARY Customer_Ref_Number = UPPER(Customer_Ref_Number)),
    Processing_Cost int check(Processing_Cost>500),
    Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)
);
  

Комментарии:

1. Ошибка и код — MySQL, поэтому я исправил тег.

Ответ №1:

MySQL начал поддерживать ограничения проверки только в MySQL 8.0.16, выпущенном в апреле 2019 года.

До этого синтаксис был разрешен (хотя, возможно, с ограничениями), но ничего не произошло.

Что происходит в вашем коде, так это то, что у вас есть:

 Processing_Cost int check(Processing_Cost>500),
Service_Charge numeric check(.12*Processing_Cost>=Service_Charge)
  

Это встроенные ограничения проверки. Это означает, что они являются частью определения столбца. Вы можете исправить это, просто добавив запятые:

 Processing_Cost int,
check (Processing_Cost > 500),
Service_Charge numeric,
check (0.12*Processing_Cost >= Service_Charge)
  

Мне нравится делать мои ограничения очевидными, поэтому я бы поместил их после столбцов и дал им имена:

 Processing_Cost int,
Service_Charge numeric,
constraint chk_customer_details_processing_cost check (Processing_Cost > 500),
constraint chk_customer_details_service_charge check (0.12*Processing_Cost >= Service_Charge)
  

Здесь находится db<>fiddle.

Примечание: Не используйте char() для типов столбцов — оно заполняет строку пробелами. Использовать varchar() .

Комментарии:

1. Большое вам спасибо @GORDON LINOFF

2. Очень полезная информация!

Я пытаюсь создать свою первую базу данных в MySQL и столкнулся с небольшой проблемой, при попытке запустить следующую таблицу я получаю следующую ошибку:

Код ошибки 3813: ограничение проверки столбца section_ck_1 ссылается на другой столбец.

Вот таблица, которую я пытаюсь написать

create table section (
course_id varchar(8),
sec_id varchar(8),
semester varchar(6) check (semester in (`Fall`, `Winter`, `Spring`, `Summer`)),
year numeric(4,0) check (year > 1701 and year < 2100),
building varchar(15),
room_number varchar(7),
time_slot_id varchar(4),
primary key (course_id, sec_id, semester, year),
foreign key(course_id) references course(course_id) on delete cascade,
foreign key (building, room_number) references classroom on delete set null);

Я считаю, что что-то не так с моими строками «семестр» или «год», хотя я не уверен, в чем проблема и как бы я ее исправил.

1 ответ

semester varchar(6) check (semester in (`Fall`, `Winter`, `Spring`, `Summer`)),

Я думаю, вы хотели использовать одинарные кавычки для создания строковых литералов четырех сезонов. Должно получиться так:

semester varchar(6) check (semester in ('Fall', 'Winter', 'Spring', 'Summer')),

Строковые литералы заключаются в одинарные кавычки.

Обратные кавычки используются для разделения идентификаторов, таких как имена таблиц и имена столбцов. Использование обратных кавычек так, как вы сделали, казалось, будто вы намеревались semester иметь то же значение, что и один из четырех других столбцов с именами Fall, Winter, Spring , Summer.


0

Bill Karwin
10 Фев 2020 в 07:39

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 3614 codesys
  • Ошибка 3809 ман
  • Ошибка 3613 камаз евро
  • Ошибка 3804 атол
  • Ошибка 3803 шкода октавия

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии