gpt4 book ai didi

mysql - SQL建表主键和外键语法

转载 作者:行者123 更新时间:2023-11-29 01:59:09 25 4
gpt4 key购买 nike

我正在为作业创建一个 MySQL 数据库,并在 phpmyadmin 中遇到语法错误 #1005。我认为它与外键有关,但如果 w3schools 是正确的,我的语法应该是好的。

这是SQL语句;

create table if not exists customers
(
id int not null auto_increment,
cust_gname varchar(20) not null,
cust_fname varchar(30) not null,
cust_street varchar(30) not null,
cust_suburb varchar(30) not null,
cust_state varchar(6) not null,
cust_postcode varchar(4) not null,
cust_email varchar(50) not null,
cust_phone varchar(12),
cust_mobile varchar(12),
cust_user_id int,
foreign key (cust_user_id) references users(id),
primary key (id)
);

create table if not exists ingredients
(
id int,
name varchar(30) not null,
primary key (id)
);

create table if not exists recipes
(
id int,
name varchar(30) not null,
recipes_menu_id int,
foreign key (recipes_menu_id) references menus(id)
image varchar(30),
primary key (id)
);

create table if not exists ingredients_recipes
(
id int,
ingredients_recipes_ingredient_id int,
foreign key (ingredients_recipes_ingredient_id) references ingredients(id),
ingredients_recipes_recipe_id int,
foreign key (ingredients_recipes_recipe_id) references recipes(id),
primary key (id)
);

create table if not exists menus
(
id int,
description varchar(30) not null,
menus_restaurant_id int,
foreign key (menus_restaurant_id) references restaurants(id),
primary key (id)
);

create table if not exists restaurants
(
id int,
name varchar(30) not null,
address1 varchar(30) not null,
address 2 varchar(30),
suburb varchar(30) not null,
state varchar(10) not null,
postcode varchar(4) not null,
primary key (id)
);

create table if not exists customers_ingredients
(
id int,
customers_ingredients_customer_id int,
foreign key (customers_ingredients_customer_id) references customers(id),
customers_ingredients_ingredient_id int,
foreign key (customers_ingredients_ingredient_id) references ingredients(id),
primary key (id)
);

create table if not exists users
(
id int,
username varchar(40) not null,
password varchar(50) not null,
group_id int,
created DATETIME,
modified DATETIME,
primary key (id)
);

create table if not exists groups
(
id int,
name varchar(10) not null,
created DATETIME,
modified DATETIME,
primary key (id)
);

最佳答案

如果您正在创建一个带有外键引用的表,它所引用的表必须已经存在。您正在脚本开头创建一个 customers 表,该表引用 users 表,该表直到接近尾声才创建。脚本中还有其他示例。

您需要以正确的顺序创建表,或者使用顶部的 set foreign_key_checks = 0; 来禁用此要求。确保在创建所有表后在最后设置 foreign_key_checks = 1

注意:您的脚本中可能还有其他语法错误 - 我还没有全部检查过。

关于mysql - SQL建表主键和外键语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19606069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com