设计一个社交网站的数据库是一个复杂的任务,需要考虑多种因素,包括用户管理、好友关系、帖子、评论、点赞、消息等。以下是一个基本的数据库设计示例,涵盖了社交网站的核心功能。
users
)存储用户的基本信息。
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50),
profile_picture_url VARCHAR(255),
bio TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
friendships
)存储用户之间的好友关系。
CREATE TABLE friendships (
user_id INT,
friend_id INT,
status ENUM('pending', 'accepted', 'declined') DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, friend_id),
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (friend_id) REFERENCES users(user_id)
);
posts
)存储用户发布的帖子。
CREATE TABLE posts (
post_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
content TEXT,
image_url VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
comments
)存储用户对帖子的评论。
CREATE TABLE comments (
comment_id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT,
user_id INT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(post_id),
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
likes
)存储用户对帖子和评论的点赞。
CREATE TABLE likes (
like_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
post_id INT,
comment_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (post_id) REFERENCES posts(post_id),
FOREIGN KEY (comment_id) REFERENCES comments(comment_id)
);
messages
)存储用户之间的私信。
CREATE TABLE messages (
message_id INT AUTO_INCREMENT PRIMARY KEY,
sender_id INT,
receiver_id INT,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (sender_id) REFERENCES users(user_id),
FOREIGN KEY (receiver_id) REFERENCES users(user_id)
);
以下是一个示例,展示如何插入和查询数据。
INSERT INTO users (username, email, password_hash, first_name, last_name)
VALUES ('john_doe', 'john@example.com', 'hashed_password', 'John', 'Doe');
INSERT INTO friendships (user_id, friend_id, status)
VALUES (1, 2, 'accepted');
INSERT INTO posts (user_id, content, image_url)
VALUES (1, 'This is my first post!', 'http://example.com/image.jpg');
INSERT INTO comments (post_id, user_id, content)
VALUES (1, 2, 'Nice post!');
INSERT INTO likes (user_id, post_id)
VALUES (2, 1);
INSERT INTO messages (sender_id, receiver_id, content)
VALUES (1, 2, 'Hello, how are you?');
SELECT * FROM posts WHERE user_id = 1;
SELECT * FROM comments WHERE post_id = 1;
SELECT u.* FROM users u
JOIN friendships f ON u.user_id = f.friend_id
WHERE f.user_id = 1 AND f.status = 'accepted';
算法大赛
Tendis系列直播
DB TALK 技术分享会
DB TALK 技术分享会
小程序·云开发官方直播课(数据库方向)
小程序·云开发官方直播课(数据库方向)
小程序·云开发官方直播课(数据库方向)
云+社区技术沙龙[第6期]
Global Day LIVE
领取专属 10元无门槛券
手把手带您无忧上云