MySQL:外键始终为0

时间:2014-08-08 17:25:06

标签: mysql sql

我正在尝试在MySQL中创建两个表,并通过用户ID(uid)和post-id(pid)将它们链接在一起。 users表具有自动递增主键uid,posts表具有主键pid。 posts表的外键是posts表的uid。由于某种原因,posts表的uid列始终为0,而​​应该指向users表的uid值。

CREATE TABLE users
(
    uid int NOT NULL AUTO_INCREMENT,
    email varchar(100) NOT NULL,
    username varchar(100) NOT NULL,
    dob varchar(10) NOT NULL,
    password varchar(100) NOT NULL,
    PRIMARY KEY (uid)
);

  CREATE TABLE posts
(
    pid int NOT NULL AUTO_INCREMENT,
    uid int NOT NULL,
    username varchar(100) NOT NULL,
    date date NOT NULL,
    title varchar(225) NOT NULL,
    content mediumtext NOT NULL,
    PRIMARY KEY(pid),
    FOREIGN KEY(uid) REFERENCES users(uid)
);

两个表的输出是:

    mysql> select *from users;
+-----+----------------+-------------+------------+----------+
| uid | email          | username    | dob        | password |
+-----+----------------+-------------+------------+----------+
|   1 | test@test.com  | Test User1  | 11/11/1111 | passwor1 |
|   2 | test2@test.com | Test User2  | 22/22/2222 | passwor2 |
|   3 | test3@test.com | Test User 3 | 33/33/3333 | passwor3 |
+-----+----------------+-------------+------------+----------+
3 rows in set (0.00 sec)

mysql> select *from posts;
+-----+-----+-------------+------------+----------------+--------------------------------------------------+
| pid | uid | username    | date       | title          | content                                          |
+-----+-----+-------------+------------+----------------+--------------------------------------------------+
|   1 |   0 | Test User 3 | 2014-08-08 | Test Post      | TEST
|   2 |   0 | Test User 3 | 2014-08-08 | Test Post 2    | Test post please ignore  
|   3 |   0 | Test User 3 | 2014-08-08 | TEST AGAIn     | Test test test test test
+-----+-----+-------------+------------+----------------+--------------------------------------------------+
3 rows in set (0.00 sec)

根据上面的数据,uid列应该是' 3'这是在users表中定义的测试用户3的uid。相反,uid列始终为0.

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

您的INSERT语句必须包含您的外键。

如果帖子与用户1之间存在关系,那么您的插入语句将如下所示:

INSERT INTO posts (uid, username, date, title, content) VALUES(1,'test','2014-08-01','title','content');