【MySQL基础】非常全面!一文掌握MySQL常用语法
MySQL是一种开放源代码的关系型数据库管理系统(RDBMS),它使用标准的SQL语言进行数据的存储、检索、更新和管理。以下是MySQL中一些常用的语法和示例代码:
- 创建数据库:
CREATE DATABASE mydatabase;
- 选择数据库:
USE mydatabase;
- 创建表:
CREATE TABLE users (
id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
- 插入数据:
INSERT INTO users (username, password, email) VALUES ('user1', 'password1', 'user1@example.com');
- 查询数据:
SELECT * FROM users;
- 更新数据:
UPDATE users SET password = 'newpassword' WHERE username = 'user1';
- 删除数据:
DELETE FROM users WHERE username = 'user1';
- 创建索引:
CREATE INDEX idx_username ON users(username);
- 创建视图:
CREATE VIEW user_view AS SELECT id, username, email FROM users;
- 创建存储过程:
DELIMITER //
CREATE PROCEDURE GetUserCount()
BEGIN
SELECT COUNT(*) FROM users;
END //
DELIMITER ;
- 调用存储过程:
CALL GetUserCount();
- 创建触发器:
CREATE TRIGGER before_user_insert
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
INSERT INTO audit_log (user_id, action) VALUES (NEW.id, 'INSERT');
END;
- 创建用户:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
- 授权用户:
GRANT SELECT, INSERT ON mydatabase.* TO 'newuser'@'localhost';
- 备份数据库:
mysqldump -u username -p mydatabase > mydatabase_backup.sql
- 恢复数据库:
mysql -u username -p mydatabase < mydatabase_backup.sql
这些是MySQL中的基础操作,实际应用中还会涉及更复杂的查询和多表操作。
评论已关闭