了解 MySQL 的基础知识和命令是使用此数据库的前提。以下是一些必须了解的 MySQL 概念和命令,包括基础的 CRUD(创建,读取,更新,删除)操作,以及一些高级功能:
sudo apt-get install mysql-server
sudo service mysql start
mysql -u root -p
CREATE DATABASE mydatabase;
USE mydatabase;
SHOW DATABASES;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
SHOW TABLES;
DESCRIBE users;
INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com');
SELECT * FROM users;
UPDATE users SET email = 'john.new@example.com' WHERE name = 'John Doe';
DELETE FROM users WHERE name = 'John Doe';
CREATE INDEX idx_users_name ON users(name);
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'newuser'@'localhost';
mysqldump -u root -p mydatabase > mydatabase.sql
mysql -u root -p mydatabase < mydatabase.sql
OPTIMIZE TABLE users;
CHECK TABLE users;
这些基础知识和命令是入门 MySQL 的基础,但 MySQL 还有更多高级功能和优化技术,值得深入学习和了解。
CREATE TABLE employees (
id INT,
name VARCHAR(50),
hired DATE
)
PARTITION BY RANGE( YEAR(hired) ) (
PARTITION p0 VALUES LESS THAN (1991),
PARTITION p1 VALUES LESS THAN (1999),
PARTITION p2 VALUES LESS THAN MAXVALUE
);
SELECT name FROM employees WHERE id IN (SELECT id FROM department WHERE name = 'HR');
CREATE VIEW hr_employees AS SELECT name FROM employees WHERE department = 'HR';
DELIMITER //
CREATE PROCEDURE GetEmployeeCount(IN dept_name VARCHAR(50), OUT count INT)
BEGIN
SELECT COUNT(*) INTO count FROM employees WHERE department = dept_name;
END //
DELIMITER ;
CALL GetEmployeeCount('HR', @count);
SELECT @count;
DELIMITER //
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
SET NEW.updated_at = NOW();
END; //
DELIMITER ;
START TRANSACTION;
UPDATE account SET balance = balance - 100 WHERE name = 'John';
UPDATE account SET balance = balance + 100 WHERE name = 'Jane';
COMMIT;
ALTER TABLE employees ADD INDEX idx_department (department);
EXPLAIN SELECT * FROM employees WHERE department = 'HR';
ALTER TABLE articles ADD FULLTEXT(title, content);
SELECT * FROM articles WHERE MATCH(title, content) AGAINST('keyword');
ALTER TABLE orders ADD FOREIGN KEY (customer_id) REFERENCES customers(id);
orders
表中的 customer_id
列被定义为 customers
表中 id
列的外键。SET GLOBAL event_scheduler = ON;
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
UPDATE mytable SET mycolumn = mycolumn + 1;
ALTER TABLE tablename ADD COLUMN newcol INT, ALGORITHM=INPLACE, LOCK=NONE;
SELECT name, salary,
AVG(salary) OVER(PARTITION BY department) as avg_salary_department
FROM employees;
WITH cte_name AS (
SELECT department, AVG(salary) as avg_salary
FROM employees
GROUP BY department
)
SELECT * FROM cte_name;
EXPLAIN
命令来查看优化器的选择。CREATE RESOURCE GROUP rg1
TYPE = USER
VCPU = 2,4
PRIORITY = 10;
这些是 MySQL 的一些额外高级功能和优化技术,这些功能和技术有助于高效地管理和查询数据库。