文章声明
#仅是个人的学习笔记记录,不得转载和供他人学习#
数据库
create DATABASE school_management;——创建数据库
use school_management;
CREATE TABLE students( ——建表
students_id int PRIMARY key auto_increment, ——主键约束,主键自增(即便为空,也会自动添加)
Name VARCHAR(50),
Age int,
class_id int,
CONSTRAINT c_s FOREIGN KEY (class_id) REFERENCES classes(class_id) ——外键约束,c_s是外键的名称,因为是classes表和students表的连接,故为c_s
语法先写本表要作为外键的列,再写外表引用的列
);
CREATE TABLE classes(
class_id int PRIMARY KEY auto_increment,
class_name VARCHAR(50)
);
desc classes;——查看表结构
desc students;
INSERT INTO classes VALUES(NULL,'Math'),(NULL,'Science');
INSERT into students VALUES(NULL,'Alice',22,1),(NULL,'Bob',20,1),(NULL,'Charlie',23,2);
SELECT * from classes where class_name='Math';
SELECT * from students ORDER BY age desc;
select * from students where class_id=(SELECT class_id from classes where class_name='Math')——子查询 先查括号里面的,再拿括号里面的出来作为条件查询,可以放在from后面作为查询结果,然后再查询结果的结果
select * from students where age>20 ORDER BY name ASC;
select name from students where age=(select MAX(age) from students);
select u.*,o.number from user u INNER JOIN orderlist o on u.id=o.uid;——内连接查询
select c.*,p.name from category c INNER JOIN product p on c.id=p.cid;
select c.*,p.name
from category c ,product p
where c.id=p.cid;——这种方法虽然没有用到Inner join的方式,但是依旧实现了上面一样的结果
查什么,去哪查,什么条件
select * from user union all select * from orderlist; ——联合查询 需要列数相同才能查出来