社交网站的数据库设计设计一个社交网站的数据库是一个复杂的任务,需要考虑多种因素,包括用户管理、好友关系、帖子、评论、点赞、消息等。以下是一个基本的数据库设计示例,涵盖了社交网站的核心功能。 数据库表设计1. 用户表 (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
);
2. 好友关系表 (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)
);
3. 帖子表 (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)
);
4. 评论表 (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)
);
5. 点赞表 (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)
);
6. 消息表 (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;
|