0、创建测试表:
CREATE TABLE students (id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(50) NOT NULL,age INT,score FLOAT
);
1、INSERT 插入数据:
INSERT INTO students (name, age, score) VALUES('lfsun1', 25, 85.5),('lfsun2', 22, 78.3),('lfsun3', 27, 92.1),('lfsun4', 23, 68.9);
2、SELECT 查询数据:
-- 查询所有学生信息
SELECT * FROM students;-- 查询年龄大于等于25岁的学生
SELECT * FROM students WHERE age >= 25;-- 查询分数最高的学生
SELECT * FROM students ORDER BY score DESC LIMIT 1;
3、UPDATE 更新数据:
-- 将id为3的学生分数更新为95.2
UPDATE students SET score = 95.2 WHERE id = 3;
5、DELETE 删除数据:
-- 删除年龄小于等于22岁的学生
DELETE FROM students WHERE age <= 22;
6、REPLACE 替换数据(只适用于有唯一索引或主键的表):
-- 假设id为1的学生信息已经存在,则替换为新的数据,否则插入新的数据
REPLACE INTO students (id, name, age, score) VALUES (2, 'lfsun-1', 21, 88.7);
7、LOAD DATA INFILE 从外部文件导入数据:
假设有一个名为data.csv的CSV文件,包含以下内容:
lfsun-5,21,88.7
lfsun-6,21,88.7
lfsun-7,27,95.2
lfsun-8,23,68.9
– 将data.csv文件中的数据导入到students表中
LOAD DATA INFILE 'data.csv的路径'
INTO TABLE students
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(name, age, score);
1、The MySQL server is running with the --secure-file-priv option so it cannot execute this statement 问题解决
2、Loading local data is disabled; this must be enabled on both the client and server sides 问题解决
8、SELECT INTO OUTFILE 将查询结果导出到外部文件:
-- 将所有学生的信息导出到students.csv文件中
SELECT * FROM students
INTO OUTFILE 'students.csv的保存路径'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n';
1、The MySQL server is running with the --secure-file-priv option so it cannot execute this statement 问题解决
9、INSERT INTO SELECT 从一个表中查询数据并插入到另一个表中:
-- 创建mature_students,其结构与students完全相同
CREATE TABLE mature_students LIKE students;
-- 将年龄大于等于25岁的学生的信息插入到mature_students表中
INSERT INTO mature_students (name, age, score)
SELECT name, age, score FROM students WHERE age >= 25;
执行修改数据的SQL语句时,请务必谨慎操作,确保备份数据以防止意外修改或删除。