今天在創建mysql表格
[SQL] create table order(
order_id int(10) PRIMARY KEY AUTO_INCREMENT,
user_id int(10),
goods_id int(10),
goods_name varchar(20) not null,
goods_type varchar(20) not null,
goods_price double not null,
order_date datetime not null,
FOREIGN KEY(user_id) REFERENCES userinfo(user_id),
foreign key(goods_id) REFERENCES hotel(goods_id)
)
出現了這個錯誤
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order(
order_id int(10) PRIMARY KEY AUTO_INCREMENT,
user_id int(10),
goods' at line 1
解決
表名使用了關鍵字,數據庫中命名要避免使用關鍵字。Hibernate中查詢語句為字段起別名,目的就是避免使用關鍵字。
(order是關鍵字,不能作為表名)
2、數據庫Cannot add foreign key constraint
解決
產生這個錯誤的多數原因有一下兩點:
1,兩張表里要設主鍵和外鍵的字段的數據類型或者數據長度不一樣 (例如這個是int 另外一個是tinyint,或者都是int,但是設置的長度不同)
2,某個表里已經有記錄了
3、兩個表的引擎不一樣,查看表的引擎語句:
show table status from 數據庫名 where name='表名';
4、要設置外鍵的字段不能為主鍵
5、改建所參考的字段必須為主鍵
6、兩個字段必須具有相同的數據類型和約束
我遇到的情況就是4、5。后面關聯的表的字段必須被設置為主鍵,才能關聯成功。
