1. 程式人生 > >MySQl的庫操作、表操作和資料操作

MySQl的庫操作、表操作和資料操作

一、庫操作

  1.1庫的增刪改查

  (1)系統資料庫:

  

  performance_schema:用來收集資料庫伺服器的效能引數,記錄處理查詢時發生的各種事件、鎖等現象

  mysql:授權庫,主要儲存系統使用者的許可權資訊

  test:MySQl資料庫系統自動建立的測試資料庫

 

  (2)資料庫操作

  建立:create database db1 charset utf8;

  (資料庫命名規則:可以是字母、數字、下劃線等的組合,不能單獨使用數字,不能使用關鍵字例如create select等)

  檢視:show databases;  或者 show create database db1; 

  選擇資料庫:use db1;

  刪除:drop database db1;

  修改:alter database db1 charset utf8;

 

二、表操作

  2.1儲存引擎介紹

  (1)類似於處理文字用txt型別,圖片用png,音樂用mp3型別,資料庫的表也有不同型別。表型別(儲存和操作此表的型別)又稱儲存引擎。MySQL資料庫提供了多種儲存引    擎。

  (2)檢視MySQL支援的儲存引擎:

    show engines\G  #檢視所有支援的儲存引擎

    

    show variables like 'storage_engine%';  #檢視正在使用的儲存引擎

    

 

  (3)部分儲存引擎的簡單介紹:有InnoDB、MyISAM、NDB、Memory、Infobright、NTSE、BLACKHOLE等;其中InnoDB是MySQL預設和最常用的一個儲存引擎,具備高可用性、高效能以及高可擴充套件性。其他詳情點選:具體介紹

  (4)使用儲存引擎

    建表時指定

    create table innodb_t1(id int,name char)engine=innodb;

    show create table innodb_t1;

 

  2.2表的增刪改查

  (1)表介紹

    

   (2)建立表 create table student(sid int(11),sname char(10),gender enum('男','女'),class_id int(11));

       檢視庫下所有表  show tables;

       往表中插入資料  insert into student values(10,'nuo','女',5);

 

   (3)查看錶結構  desc student;  或者 show create table student\G;  #檢視詳細表結構,可加\G

     

   

   (4)修改表結構

    (4.1)修改儲存引擎  alter table student engine=NDB;

    (4.2)新增欄位  alter table student add age int not null;

    (4.3)刪除欄位  alter table student drop age;

    (4.4)修改欄位型別  alter table student modify age int(9) not null primary key;

    (4.5)刪除主鍵  alter table student drop primary key;

   (5)複製表

    複製表結構+記錄 (key不會複製: 主鍵、外來鍵和索引)
    mysql> create table new_service select * from service;

    只複製表結構
    mysql> select * from service where 1=2;        //條件為假,查不到任何記錄
    Empty set (0.00 sec)
    mysql> create table new1_service select * from service where 1=2;  
    Query OK, 0 rows affected (0.00 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    mysql> create table t4 like employees;

  (6)刪除表 drop table student;

  2.3資料型別

    mysql常用資料型別有 數值型別 int , float 等、字串型別 char varchar 、日期型別 datatime等、列舉型別和集合型別

    (1)數值型別

    

    (2)日期型別

    

    

    

    (3)字串型別 char 和 varchar

    

    (char定長,varchar不定長,雖然varchar使用起來較為靈活,但是從整個系統的效能角度來說,char資料型別的處理速度更快,有時甚至可以超出varchar處理速度的      50%。因此,在選擇時,應該綜合考慮,以求達到最佳的平衡。)

    (4)列舉型別和集合型別

    列舉enum(),集合set();列舉單選,集合可多選;

    

  2.4完整性約束

    not null (非空)、default (預設)、primary key(主鍵,唯一)、foreign key(外來鍵)、unique(唯一)、auto_increment(自增,整數型別且為主鍵)

    (1)設定唯一約束unique:  

方法一:
create table department1(
id int,
name varchar(20) unique,
comment varchar(100)
);


方法二:
create table department2(
id int,
name varchar(20),
comment varchar(100),
constraint uk_name unique(name)
);

create table service(
id int primary key auto_increment,
name varchar(20),
host varchar(15) not null,
port int not null,
unique(host,port) #聯合唯一
);
View Code

    

    (2)primary key

 1 # 單列做主鍵
 2 #方法一:not null+unique
 3 create table department1(
 4 id int not null unique, #主鍵
 5 name varchar(20) not null unique,
 6 comment varchar(100)
 7 );
 8 
 9 #方法二:在某一個欄位後用primary key
10 create table department2(
11 id int primary key, #主鍵
12 name varchar(20),
13 comment varchar(100)
14 );
15 
16 #方法三:在所有欄位後單獨定義primary key
17 create table department3(
18 id int,
19 name varchar(20),
20 comment varchar(100),
21 constraint pk_name primary key(id); #建立主鍵併為其命名pk_name
單列做主鍵
1 create table service(
2 ip varchar(15),
3 port char(5),
4 service_name varchar(10) not null,
5 primary key(ip,port)
6 );
多列做主鍵

    

    (3)foreign key

#表型別必須是innodb儲存引擎,且被關聯的欄位,即references指定的另外一個表的欄位,必須保證唯一
create table department(
id int primary key,
name varchar(20) not null
)engine=innodb;

#dpt_id外來鍵,關聯父表(department主鍵id),同步更新,同步刪除
create table employee(
id int primary key,
name varchar(20) not null,
dpt_id int,
constraint fk_name foreign key(dpt_id)
references department(id)
on delete cascade
on update cascade 
)engine=innodb;


#先往父表department中插入記錄
insert into department values
(1,'歐德博愛技術有限事業部'),
(2,'艾利克斯人力資源部'),
(3,'銷售部');


#再往子表employee中插入記錄
insert into employee values
(1,'egon',1),
(2,'alex1',2),
(3,'alex2',2),
(4,'alex3',2),
(5,'李坦克',3),
(6,'劉飛機',3),
(7,'張火箭',3),
(8,'林子彈',3),
(9,'加特林',3)
;
View Code

 

    (4)auto_increment

#不指定id,則自動增長
create table student(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') default 'male'
);


#應該用truncate清空表,比起delete一條一條地刪除記錄,truncate是直接清空表,在刪除大表時用它
mysql> truncate student;
Query OK, 0 rows affected (0.01 sec)


#設定步長
sqlserver:自增步長
    基於表級別
    create table t1(
        id int。。。
    )engine=innodb,auto_increment=2 步長=2 default charset=utf8

mysql自增的步長:
    show session variables like 'auto_inc%';

    #基於會話級別
    set session auth_increment_increment=2 #修改會話級別的步長

    #基於全域性級別的
    set global auth_increment_increment=2 #修改全域性級別的步長(所有會話都生效)



清空表:

delete from t1; #如果有自增id,新增的資料,仍然是以刪除前的最後一樣作為起始。

truncate table t1;資料量大,刪除速度比上一條快,且直接從零開始,
View Code

   

    

三、資料操作

  3.1資料的增刪改

   假設已經建了一張表student

    增加:insert into student values

        (值1,值2,值3...),

        (值1,值2,值3...),

        (值1,值2,值3...);

    刪除:delete from student

        where condition

    更新:update student set

        欄位1=值1,

        欄位2=值2,

        where condition;

 

  3.2單表查詢

   一、單表查詢基本語法

    select 欄位1,欄位2... from 表名

      where 條件

      group by field

      having 篩選

      order by field

      limit 限制條數

   二、關鍵字在執行中的優先順序

    重點中的重點:關鍵字的執行優先順序

      from

      where

      group by

      having

      select

      distinct   去重

      order by

      limit

   三、where約束

      1、比較運算子:> < >=  <= <>  !=

      2、between 80 and 100 值在10到20之間

      3、in(80,90,100) 值是10或20或30

      4、like 'egon%'
        pattern可以是%或_,
        %表示任意多字元
        _表示一個字元

      5、邏輯運算子:在多個條件直接可以使用邏輯運算子 and or not

   四、group by 分組

    如果我們用unique的欄位作為分組的依據,則每一條記錄自成一組,這種分組沒有意義     多條記錄之間的某個欄位值相同,該欄位通常用來作為分組的依據

   五、聚合函式

    #強調:聚合函式聚合的是組的內容,若是沒有分組,則預設一組

    示例:

      SELECT COUNT(*) FROM employee;

      SELECT COUNT(*) FROM employee WHERE depart_id=1;

      SELECT MAX(salary) FROM employee;

      SELECT MIN(salary) FROM employee;

      SELECT AVG(salary) FROM employee;

      SELECT SUM(salary) FROM employee;

      SELECT SUM(salary) FROM employee WHERE depart_id=3; 

   六、having

    having和where不一樣的地方在於:

      1、執行優先順序從高到低  where > group by > having

      2、where 在group by 之前,因此where中可以有任意欄位,但是絕對不可以使用聚       合函式

      3、having發生在分組group by之後,因此可以使用分組的欄位,無法直接取到其他       欄位,可以使用聚合函式。

   七、order by 查詢排序

      按單列排序:

      SELECT * FROM employee ORDER BY salary;

      SELECT * FROM employee ORDER BY salary ASC;

      SELECT * FROM employee ORDER BY salary DESC;

 

      按多列排序:先按照age排序,如果年紀相同,則按照薪資排序

      SELECT * from employee

      ORDER BY age, salary DESC;

   八、使用正則表示式查詢

      SELECT * FROM employee WHERE name REGEXP '^ale';

      SELECT * FROM employee WHERE name REGEXP 'on$';

      SELECT * FROM employee WHERE name REGEXP 'm{2}';

      小結:

      對字串匹配的方式

      WHERE name = 'egon';

      WHERE name LIKE 'yua%';

      WHERE name REGEXP 'on$';

 

  3.3多表查詢

    多表連線查詢

    符合條件連線查詢

    子查詢

 

    一、多表連線查詢

      select 欄位 

        from 表一  inner|left|right  join 表二

        on 表一.欄位 = 表二.欄位;

      (1)交叉連線:不適用任何匹配條件,生成笛卡爾積

        假設我們已經生成employee,department兩張表

        select * from employee,department;

       (2) 內連線:只連線匹配的行

        select employee.id department.name 

          from employee inner join department

          on employee.id = department.id;

       (3)外連線之左連線:優先顯示左表全部記錄

        select employee.id department.name 

          from employee left join department

          on employee.id = department.id;

       (4)外連線之右連線:優先顯示右表全部記錄

        right join ,其他參考左連線。

       (5)全外連線 :顯示左右兩個表全部記錄

        select * from employee left join department on employee.dep_id = department.id

        union

        select * from employee right join department on employee.dep_id = department.id;

 

 

   二、符合條件連線查詢

     #示例:以內連線的方式查詢employee和department表,並且以age欄位的升序方式顯示

      select employee.id,employee.name,employee.age,department.name

        from employee,department

        where employee.dep_id = department.id and age > 25

        order by age asc;   

 

   三、子查詢

      # 子查詢是將一個查詢語句巢狀在另一個查詢語句中。

      #2:內層查詢語句的查詢結果,可以為外層查詢語句提供查詢條件。

      #3:子查詢中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等關鍵字

      #4:還可以包含比較運算子:= 、 !=、> 、<等

1 帶IN關鍵字的子查詢
#查詢平均年齡在25歲以上的部門名
select id,name from department
    where id in 
        (select dep_id from employee group by dep_id having avg(age) > 25);

#檢視技術部員工姓名
select name from employee
    where dep_id in 
        (select id from department where name='技術');

#檢視不足1人的部門名
select name from department
    where id in 
        (select dep_id from employee group by dep_id having count(id) <=1);
2 帶比較運算子的子查詢
#比較運算子:=、!=、>、>=、<、<=、<>
#查詢大於所有人平均年齡的員工名與年齡
mysql> select name,age from emp where age > (select avg(age) from emp);
+---------+------+
| name | age |
+---------+------+
| alex | 48 |
| wupeiqi | 38 |
+---------+------+
rows in set (0.00 sec)


#查詢大於部門內平均年齡的員工名、年齡
select t1.name,t1.age from emp t1
inner join 
(select dep_id,avg(age) avg_age from emp group by dep_id) t2
on t1.dep_id = t2.dep_id
where t1.age > t2.avg_age;
3 帶EXISTS關鍵字的子查詢
EXISTS關字鍵字表示存在。在使用EXISTS關鍵字時,內層查詢語句不返回查詢的記錄。
而是返回一個真假值。True或False
當返回True時,外層查詢語句將進行查詢;當返回值為False時,外層查詢語句不進行查詢
#department表中存在dept_id=203,Ture
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=200);
+----+------------+--------+------+--------+
| id | name       | sex    | age  | dep_id |
+----+------------+--------+------+--------+
|  1 | egon       | male   |   18 |    200 |
|  2 | alex       | female |   48 |    201 |
|  3 | wupeiqi    | male   |   38 |    201 |
|  4 | yuanhao    | female |   28 |    202 |
|  5 | liwenzhou  | male   |   18 |    200 |
|  6 | jingliyang | female |   18 |    204 |
+----+------------+--------+------+--------+

#department表中存在dept_id=205,False
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=204);
Empty set (0.00 sec)
View Code