{MySQL} 数据库约束& 表的关系& 新增&&删除& 修改& 查询
在MySQL中,数据库表的关系可以通过外键(FOREIGN KEY)约束来定义。以下是创建表、添加数据、删除数据、修改数据以及查询数据的基本SQL语句示例。
创建表:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
);
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
title VARCHAR(50),
content TEXT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
添加数据:
INSERT INTO users (username, password) VALUES ('user1', 'pass1');
INSERT INTO users (username, password) VALUES ('user2', 'pass2');
INSERT INTO posts (user_id, title, content) VALUES ((SELECT id FROM users WHERE username='user1'), 'Post 1', 'Content 1');
INSERT INTO posts (user_id, title, content) VALUES ((SELECT id FROM users WHERE username='user2'), 'Post 2', 'Content 2');
删除数据:
DELETE FROM users WHERE id = 1;
DELETE FROM posts WHERE user_id = 1;
修改数据:
UPDATE users SET password = 'newpass' WHERE id = 1;
UPDATE posts SET title = 'New Post 1' WHERE user_id = 1;
查询数据:
SELECT * FROM users;
SELECT * FROM posts WHERE user_id = 1;
这些操作都应在定义好的数据库上下文中执行,并确保遵守所有已定义的约束。
评论已关闭