3

我正在为作业创建一个 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)
);
4

1 回答 1

4

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

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

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

于 2013-10-26T11:27:39.483 回答