混合表
继续上次的内容
新建一个表posts,将上次的users表中的id作为posts的外键
CREATE TABLE posts(
id INT auto_increment,
user_id INT,
title VARCHAR(100),
body text,
publish_date DATETIME DEFAULT CURRENT_TIMESTAMP, #时间戳的默认值
PRIMARY KEY(ID),
FOREIGN KEY(user_id) REFERENCES users(id) #★
);
插入了几条记录,
通过主键将他们关联起来
SELECT users.first_name, users.last_name, posts.title, posts.publish_date
FROM users
INNER JOIN posts
ON users.id = posts.user_id
ORDER BY posts.title;
再新建一个评论表,与使用者和帖子联系起来
CREATE TABLE comments(
id INT AUTO_INCREMENT,
post_id INT,
user_id INT,
body TEXT,
publish_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id),
FOREIGN KEY(post_id) REFERENCES posts(id),
FOREIGN KEY(user_id) REFERENCES users(id)
);
插入几条记录
INSERT INTO comments(post_id, user_id, body)
VALUES (1, 3, "1st comment by user_3"),
(2, 3, "2nd comment by user_3"),
(4, 5, "3rd comment by user_5"),
(3, 4, "4th comment by user_4");
连接多个表
SELECT
comments.body, posts.title,
CONCAT(users.first_name,'-',users.last_name) AS 'Name'
FROM comments
LEFT JOIN posts ON posts.id = comments.post_id
INNER JOIN users ON users.id = comments.user_id
ORDER BY posts.title;
为啥此时在右边加入会出现下面这种情况捏
SELECT
comments.body, posts.title, users.first_name
FROM comments
LEFT JOIN posts ON posts.id = comments.post_id
RIGHT JOIN users ON users.id = comments.user_id
ORDER BY posts.title;
各种JOIN之间的区别
这就需要了解一下各种JOIN之间的区别了, 网上有张图流传的较为广泛
以我建的两个表举例
comments表(下面统称为C表)
users表(下面统称为U表)
表C左连接表U,以左为主,则表示以表C为主,关联上表U的数据,查出来的结果显示左边的所有数据,右边显示的是和左边有交集部分的数据
SELECT
comments.id,comments.user_id,comments.body, users.last_name
FROM comments
LEFT JOIN users ON users.id = comments.user_id;
若是右接U表,则会是这样