Mysql 基础命令使用

目录

  • 1. 安装 Mysql
  • 2. 基础命令使用

1. 安装 Mysql

Windows10下超详细Mysql安装

2. 基础命令使用

登录数据库

mysql -u root -p

创建数据库:

CREATE DATABASE database_name;

列出所有数据库:

SHOW DATABASES;

选择数据库:

USE database_name;

创建一个名为student的表,其中定义了id,name,age,gender四个变量,id和age同为INT型变量,但id设置为了主键并且会自动递增,name和gender都为字符型变量但name设置了不能为空:

CREATE TABLE student( 
    id INT(11) PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(50) NOT NULL,
    age INT(11),
    gender VARCHAR(10) 
);

向表中插入数据:

INSERT INTO student(name,age,gender) VALUES('张三',18,'男'); 
INSERT INTO student(name,age,gender) VALUES('李四',20,'女');
INSERT INTO student(name,age,gender) VALUES('王五',22,'男');

查询student表中所有的数据:

SELECT * FROM student;

查询年龄>20的学生:

SELECT * FROM student WHERE age>20;

查询女学生:

SELECT * FROM student WHERE gender="女";

更改数据,将id为1的学生(张三)名字更改为(陈六)

UPDATE student SET name='陈六' WHERE id=1;

删除数据,删除id为2的学生:

DELETE FROM student WHERE id=2;

按照年龄升序排序:

SELECT * FROM student ORDER BY age ASC;

按照年龄降序排序:

SELECT * FROM student ORDER BY age DESC;

查询前三条数据:

SELECT * FROM student LIMIT 3;

查询第二条到第四条数据:

SELECT * FROM student LIMIT 1,3;

然后创建一个名为score的表:

CREATE TABLE score( 
    id INT(11) PRIMARY KEY AUTO_INCREMENT, 
    student_id INT(11) NOT NULL, 
    subject VARCHAR(50) NOT NULL, 
    score INT(11) NOT NULL 
);

向score表中插入数据:

INSERT INTO score(student_id,subject,score) VALUES(1,'数学',90); 
INSERT INTO score(student_id,subject,score) VALUES(1,'英语',80); 
INSERT INTO score(student_id,subject,score) VALUES(2,'数学',85); 
INSERT INTO score(student_id,subject,score) VALUES(2,'英语',88); 
INSERT INTO score(student_id,subject,score) VALUES(3,'数学',92); 
INSERT INTO score(student_id,subject,score) VALUES(3,'英语',95);

查询每个学生的平均成绩:

SELECT student.id,student.name,AVG(score.score) AS average FROM student,score WHERE student.id=score.student_id GROUP BY student.id;

你可能感兴趣的:(数据库,mysql,数据库)