Sql不会让我创建这些表,因为语法错误可以有人帮助我。
drop table users;
drop table intrest;
drop table friendships;
create table users(
id INT,
Fname char(15),
Lname char(15),
email char(20),
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone INT,
User_password char(15),
primary key (id),
foreign key (intrest_id) references intrest(id)
);
create table Intrests(
id INT,
description char(30),
Primary key (id),
foreign key (users_id) references users(id)
);
create table User_intrest(
foreign key (users_id) references users(id),
foreign key (intrest_id) references intrest(id)
);
create table friendships(
User_1_id INT,
User_2_id INT,
description Char(20),
foreign key (users_id) references users(id)
);
答案 0 :(得分:1)
create table Intrests( id INT, description char(30),
Primary key (id),
foreign key (users_id) references users(id) );
create table User_intrest( foreign key (users_id) references users(id),
foreign key (intrest_id) references intrest(id) );
对于兴趣表,users_id列在哪里定义? user_interest表的列定义?
答案 1 :(得分:1)
您有周期性的FK关系:
Users
有Interests(id)
作为FK,Interests
有user(id)
作为FK。
您不需要 EITHER ,因为您有一个user_intrest
表来链接它们!
您还有几个包含表格名称的拼写错误,例如intrests
和intrest
。
此外,您应该将User
中的Friendships
字段设为FK Users
,我不确定您为何需要第三个不相关的Users_Id
字段。
答案 2 :(得分:1)
您遇到的第一个(很多)语法错误是
create table users(
...
primary key (id),
foreign key (intrest_id) references intrest(id) <--- there is no table intrest
);
我建议:
但是停止!不要只是复制粘贴。试着看看MySQL为什么会给你错误信息:Key column 'intrest_id' doesn't exist in table
,这不是你得到的错误吗?
尝试先修复该错误。你有什么要做的?在表格intrest_id
中添加users
字段,而不只是将其声明为FOREIGN KEY
。 (最终它不是一个有用的领域,但无论如何都要这样做。)
然后重新运行查询并尝试修复下一个错误。逐一。如果你真的卡在某个地方,那么,你知道一个提问的网站:)
因此,尝试逐个修复错误,直到您的脚本运行完全没有任何错误。您将学到的不仅仅是复制和粘贴任何答案。
CREATE TABLE Users(
id INT,
Fname char(15),
Lname char(15),
email char(50), <-- 20 is too small for emails
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone char(20), <-- phone should be char, not INT
user_password char(15),
PRIMARY KEY (id)
); <-- You don't really need a foreign key to Interests,
<-- that's why you have the User_interest "middle" table
CREATE TABLE Interests(
id INT,
description char(30),
PRIMARY KEY (id)
); <-- You don't really need a foreign key to Users,
<-- for the same reasons.
CREATE TABLE User_interest(
user_id INT, <-- These foreign keys are
interest_id INT, <-- good, but you need to
<-- declare them as fields, too
PRIMARY KEY (user_id, interest_id), <-- It's good if all tables have PK
FOREIGN KEY (user_id) REFERENCES Users(id),
FOREIGN KEY (interest_id) REFERENCES Interests(id)
);
CREATE TABLE Friendships(
user_1_id INT,
user_2_id INT,
description char(20),
PRIMARY KEY (user_1_id, user_2_id),
FOREIGN KEY (user_1_id) REFERENCES Users(id),
FOREIGN KEY (user_2_id) REFERENCES Users(id)
);