MySQL 基础面试题
1. 如何创建数据库?
CREATE DATABASE your_database_name;
2. 如何创建表?
CREATE TABLE your_table_name (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT
);
3. 如何插入数据到表中?
INSERT INTO your_table_name (name, age) VALUES ('John', 25);
4. 如何更新表中的数据?
UPDATE your_table_name SET age = 26 WHERE name = 'John';
5. 如何删除表中的数据?
DELETE FROM your_table_name WHERE name = 'Jane';
6. 如何删除表?
DROP TABLE your_table_name;
7. 如何修改表结构(添加列、删除列、修改列)?
ALTER TABLE your_table_name ADD COLUMN new_column INT;
ALTER TABLE your_table_name DROP COLUMN old_column;
ALTER TABLE your_table_name MODIFY COLUMN column_name VARCHAR(255);
8. 如何查询表中的数据?
SELECT * FROM your_table_name;
9. 如何使用 WHERE 子句进行条件查询?
SELECT * FROM your_table_name WHERE age > 20;
10. 如何对查询结果进行排序?
SELECT * FROM your_table_name ORDER BY age DESC;
11. 如何使用聚合函数(如 SUM、AVG、COUNT)?
SELECT SUM(age), AVG(age), COUNT(*) FROM your_table_name;
12. 如何使用 GROUP BY 子句进行分组查询?
SELECT name, COUNT(*) FROM your_table_name GROUP BY name;
13. 如何使用 JOIN 进行表连接操作?
SELECT orders.order_id, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id;
14. 如何使用子查询(Subquery)?
SELECT product_name
FROM products
WHERE price > (SELECT AVG(price) FROM products);
15. 如何使用 LIMIT 子句限制查询结果数量?
SELECT * FROM sales LIMIT 10;
16. 如何使用 UNION 合并查询结果?
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
17. 如何创建索引?
CREATE INDEX idx_product_name ON products (product_name);
18. 如何删除索引?
DROP INDEX idx_product_name ON products;
19. 如何备份和恢复数据库?
mysqldump -u username -p dbname > backup.sql
mysql -u username -p dbname < backup.sql
20. 如何执行事务操作?
START TRANSACTION;
INSERT INTO orders (customer_id, amount) VALUES (1, 100);
UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 123;
COMMIT; -- 提交事务
-- 或 ROLLBACK; -- 回滚事务
21. 如何创建存储过程?
DELIMITER //
CREATE PROCEDURE GetOrderCount(IN customerID INT)
BEGIN
SELECT COUNT(*) FROM orders WHERE customer_id = customerID;
END //
DELIMITER ;
22. 如何调用存储过程?
23. 如何创建触发器?
DELIMITER //
CREATE TRIGGER UpdateTotalSpent
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
UPDATE customers SET total_spent = total_spent + NEW.amount WHERE customer_id = NEW.customer_id;
END //
DELIMITER ;
24. 如何执行批量导入数据?
LOAD DATA INFILE 'data.csv'
INTO TABLE your_table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(column1, column2, ...);
25. 如何使用 ALTER TABLE 修改表的字符集和排序规则?
ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
26. 如何使用 SHOW 命令查看数据库、表、列信息?
SHOW DATABASES;
SHOW TABLES;
SHOW COLUMNS FROM your_table_name;
27. 如何使用 EXPLAIN 分析查询语句的执行计划?
EXPLAIN SELECT * FROM your_table_name WHERE column_name = 'value';
28. 如何进行全文索引搜索?
SELECT * FROM articles WHERE MATCH(content) AGAINST('search_keyword');
29. 如何查找重复的记录?
SELECT order_id, COUNT(*) FROM orders GROUP BY order_id HAVING COUNT(*) > 1;
30. 如何处理日期和时间数据?
SELECT * FROM orders WHERE order_date > '2023-01-01';