sql語句:增删改查,其中 增、删、改隻用于單表
多表級聯删除,級聯更新有時候會出現(例如:删除父類别,子類别也會被删除)
多表查詢:多表聯查、子查詢
建表語句: 一般不需要語句建表,語句了解認識即可,手動在mysql軟體中 右鍵,點選設計表即可。
CREATE TABLE oper_user(
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
);
CREATE TABLE 表名(
字段1 字段類型 字段條件,
name VARCHAR(255) NOT NULL,
);
PRIMARY KEY // 關鍵字
VARCHAR(255) // 字段精度
NOT NULL // 不能為空
舉例 教室表和學生表 進行查詢:
// 教室表:
CREATE TABLE classroom(
id INT PRIMARY KEY, // 教室id
name VARCHAR(255) NOT NULL // 教室名字
)
// 學生表
CREATE TABLE student(
id INT PRIMARY KEY, // 學生id
name VARCHAR(255) NOT NULL, // 學生名字
score DOUBLE(10,2), // 學生成績
classid INT //教室id
)
// DOUBLE(10,2)表示 數字最大共10位,小數位最多有兩位
// 大寫的單詞代表關鍵字
教室表:
id | name |
1 | 教室一 |
2 | 教室二 |
學生表:
id | name | score | classid |
1 | 張三 | 43 | 1 |
2 | 李四 | 54 | 1 |
3 | 王五 | 21 | 2 |
4 | 小二 | 12 | 2 |
多表聯查:1。同時查詢多張表:
笛卡爾積:(a表有m條記錄,b表有n條記錄,會傳回m*n條記錄);
select * from `classroom`,`student` // 查兩個表的所有字段 會傳回全排列組合(沒有意義)
如果查詢n張表,必須指定n-1個公共列的條件,否則就會産生笛卡爾積,
上面教室表和學生表中教室id即為公共列
select * from `classroom`,`student` where classroom.id=student.classid
// 查詢教室表中的id等于學生表中的classid的資料
select classroom.id from `classroom`,`student` where classroom.id=student.classid
// 查詢教室表中的id等于學生表中的classid的教室id
select score from `classroom`,`student` where classroom.id=student.classid
// 查詢教室表中的id等于學生表中的classid的成績,最好是用student.score
查詢教室一的學生資訊:
select student.* from `classroom`,`student` where classroom.id=student.classid and classroom.name='教室一'
// 查詢教室表和學生表中教室名叫 教室一 的,學生資訊
// student.* 即為隻傳回符合條件的學生表裡的資訊即
// * 傳回符合條件的學生表和教室表的資訊
// classroom.* 同理為傳回符合條件的教室表裡的資訊
查詢張三的教室資訊:
select classroom.* from `classroom`,`student` where classroom.id=student.classid and student.name='張三'
假如現在教室表又增加一個教室三:
id | name |
1 | 教室一 |
2 | 教室二 |
3 | 教室三 |
但是學生表裡沒有在教室三的學生:
id | name | score | classid |
1 | 張三 | 43 | 1 |
2 | 李四 | 54 | 1 |
3 | 王五 | 12 | 2 |
4 | 小二 | 21 | 2 |
//這個時候使用學生id和教室id對應是差不到教室三的
select * from `classroom`,`student` where classroom.id=student.classid
多表聯查:2。左連接配接:以左表為基準(左表是主表)、左表中滿足條件的記錄會查詢出來,不滿足條件的也會被查詢出來;
select * from `classroom` left join `student` on classroom.id=student.classid
// 滿足學生id和教室id相等的資料,教室沒有學生的也會顯示出來
傳回結果:
id | name | id1 | name1 | score | classid |
1 | 教室一 | 1 | 張三 | 43 | 1 |
1 | 教室一 | 2 | 李四 | 54 | 1 |
2 | 教室二 | 3 | 王五 | 21 | 2 |
2 | 教室二 | 4 | 小二 | 12 | 2 |
3 | 教室三 | null | null | null | null |
多表聯查:2。右連接配接:以右表為基準(右表是主表)、右表中滿足條件的記錄會查詢出來,不滿足條件的也會被查詢出來;
select * from `student` right join `classroom` on classroom.id=student.classid
// 滿足學生id和教室id相等的資料,教室沒有學生的也會顯示出來
結果同上
多表聯查:3。内連接配接:查詢滿足條件的資料
select * from `student` inner join `classroom` on classroom.id=student.classid