《深入淺出MySQL》 讀書筆記一:SQL基礎
阿新 • • 發佈:2019-01-07
一、SQL分類
1、create、drop、alter等,屬於 資料定義語言
2、insert、delete、update、select 屬於 資料操縱語句
3、grant等 定義訪問許可權和安全級別 屬於 資料控制語句
二、資料定義語句
mysql -uroot -p 輸入密碼 登陸MySQL show databases; 檢視所有資料庫 create database test; 建立test資料庫 use test 將 資料庫切換為 test show tables; 檢視所有的表 drop database test; 刪除test資料庫 CREATE TABLE test ( id INT NOT NULL auto_increment PRIMARY KEY, NAME VARCHAR (10) ); 使用預設引擎建立 test表 show variables like '%engine%'; 檢視預設的儲存引擎 desc test; 檢視test表結構 show create table test \G; 檢視建立test表的語句 drop table test; 刪除test表 alter table test modify name varchar(20); 修改表字段型別 alter table test add column age int; 增加表字段 alter table test drop column age; 刪除表字段 alter table test change name name1 varchar(20); 修改表的 名稱和型別 alter table test rename test11; 修改表名稱
三、資料操作語句
insert into test11 (id, name1) values (1, '測試'); 插入資料 insert into test11 values (1, '測試'); 不帶列名 按列名順序儲存 select * from test11; 查詢資料 update test11 set name1='更新測試' where id = 1; 按條件更新資料 update a,b set a.name = b.name where a.code = b.code; 根據一張表的資料更新另一張表的資料 delete from test11 where id = 1; 刪除資料 不加where則刪除全部 select * from a,b where a.code = b.code; 內連線查詢 只顯示相互匹配的 select * from a left join b where a.code = b.code; 左連線查詢 a表中的資料全部展示 b中不匹配的顯示 null select * from a right join b where a.code = b.code; 又連線查詢 select distinct code from a; 去重查詢 code select * from a order by age desc,score asc; 排序查詢 select count(type), type from a group by type; 聚合查詢 group by 配合 聚合函式 sum() count() select * from a where deptno in (select deptno from dept); 子查詢 可以優化為 連線查詢 如下 select a.* from a,b where a.deptno = b.deptno; 連線查詢 相對子查詢 不用建立中間表 select deptno from a union select deptno from b; 去重聯合 union all 不去重