MySQL数据库是一种关系型数据库管理系统,它使用SQL(结构化查询语言)进行数据操作。以下是一些常用的SQL语句及其示例:
创建数据库:
CREATE DATABASE mydb;
删除数据库:
DROP DATABASE mydb;
创建表:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
删除表:
DROP TABLE users;
插入数据:
INSERT INTO users (username, password, email) VALUES ('张三', '123456', 'zhangsan@example.com');
更新数据:
UPDATE users SET email = 'zhangsan_new@example.com' WHERE id = 1;
删除数据:
DELETE FROM users WHERE id = 1;
查询数据:
SELECT * FROM users;
查询指定条件的数据:
SELECT * FROM users WHERE username = '张三';
排序数据:
SELECT * FROM users ORDER BY created_at DESC;
分组数据:
SELECT email, COUNT(*) as count FROM users GROUP BY email;
连接多个表:
SELECT u.username, p.title, p.content
FROM users u
JOIN posts p ON u.id = p.user_id;
子查询:
SELECT * FROM users WHERE id IN (SELECT user_id FROM posts WHERE title LIKE '%Python%');
聚合函数:
SELECT COUNT(*) as total_users, AVG(age) as average_age FROM users;
限制查询结果的数量:
SELECT * FROM users LIMIT 10;
以上是一些基本的MySQL SQL语句及其示例。在实际开发中,还涉及到更多的SQL语句和技巧,如索引、存储过程、触发器等。希望这些示例能帮助你更好地理解和使用MySQL数据库。