天天看點

MySQL[一]

一丶概述

1·什麼是MySQL丶Oracle丶SQLite丶Access丶MS SQL Server等?

  答:放資料的倉庫,如:在ATM的實列中我們建立了一個db目錄,稱其為資料庫·

2·什麼事MySQL,Oracle,SQLite,Access,MS SQL Server等?

  答:他們均是一個軟體,都有兩個主要的功能,

  ·1.強資料儲存到檔案或記憶體

  ·2.接收特定的指令,然後對檔案進行相對應的操作·

3丶什麼是SQL?

  答:上述提到MySQL等軟體可以接收指令,并做出相對應的操作 ,由于指令中可以包含删除檔案,擷取檔案内容等衆多操作,對于編寫的指令就是SQL語句·

二丶下載下傳安裝

MySQL是一個關系型資料庫管理系統,由瑞典MySQL AB公司開發,目前屬于Oracle旗下公司.MySQL最流行的關系型資料庫管理系統,在WEB應用方面MySQL是最好的RDBMS(Relational Database Manaqement System,關系資料庫管理系統)應用軟體之一·

想要MySQL來儲存并操作資料,則需要做幾件事情:

  1·安裝MySQL服務端

  2·安裝MySQL用戶端

  3·[用戶端]連接配接[服務端]

  4·[用戶端]發送指令給[服務端MySQL]服務的接收指令并執行相應操作(增删改查等)

下載下傳:

   

http:

//dev.mysql.com/downloads/mysql/

服務端啟動:

  mysql.server start

用戶端連接配接:

連接配接;
       mysql - h host -u user -p

常見錯誤:
            ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), it means that the MySQL server daemon (Unix) or service (Windows) is not running.

退出:
     QUIT 或者 Conntrol+D
      

  三丶資料庫操作

1·顯示資料庫

  

SHOW DATABASES;           #注意一定要加分号
      

  預設資料庫

mysql - 使用者權限相關資料

test - 用于使用者測試資料

information_schema - MySQL本身架構相關資料
      

2·建立資料庫

#utf-8
CREATE DATABASE 資料庫名稱 DEFAULT CHARSET utf-8 COLLATE utf8_general_ci;


#gbk
CREATE DATABASE 資料庫名稱 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;
      

3·使用資料庫

USE db_name;
      

  顯示目前使用的資料庫中所有表:SHOW TABLES;

 4·使用者管理

建立使用者
          create user '使用者名'@'IP位址' identified by '密碼';
删除使用者
          drop user '使用者名'@'ip位址';
修改使用者
          rename user '使用者名'@'IP位址';to'新使用者名'@'IP位址';
修改密碼
          set password for '使用者名'@'IP位址' = password('新密碼')

注:使用者權限相關資料儲存在mysql資料庫的user表中,是以也可以直接對其進行操作(不建議)      

5·授權管理

show grants for '使用者名'@'IP位址'                --檢視權限

grant 權限 on資料庫.表 to  '使用者名'@'IP位址'   -- 權限

revoke 權限 on資料庫.表 from   '使用者名'@'IP位址'   --取消權限
      
all.privileges          除grant外的所有權限

select                    僅查權限

select,insert          查和插入權限
.....

usage                   無通路權限

alter                     使用alter table

alter routine         使用alter procedure 和 drop procedure

create                  使用create table

create routine       使用create procedure

create temporary tables     使用create temporary tables

create user        使用create user,drop user,reanme user和revoke all privileges

create view        使用create view

delete                使用delete

drop                   使用drop table

execute               使用call和存儲過程

file                     使用select info onto outfile 和 load data infile

grant option        使用grant 和 revoke

index                    使用index

insert                   使用insert

lock tables           使用lock table

process               使用show full processlist

select                   使用select

show databases     使用show databases

show vies             使用show view

update                 使用update

reload                   使用flush

shutdown             使用mysqladmin shutdown(關閉MySQL)

replication            伺服器位置的通路

replication slave    由複制從屬使用
      
#對于資料庫

對于目标資料庫以及内部其他:
資料庫名.*             資料庫中的所有

資料庫名.表            指定資料庫中的某張表

資料庫名.存儲過程    指定資料庫中的存儲過程

*.*                        所有資料庫
      

 

#對于使用者和IP

           使用者名@IP位址                         使用者隻能在改IP下才能通路
      
           使用者名@192.168.1.%              使用者名隻能在改IP段下才能通路(統配符%表示任意)
           使用者名@%                               使用者可以再任意IP下通路(預設IP位址為%)
      
#示列
         grant all privileges on db1.tb1 TO '使用者名'@'IP'
     
         grant select on db1.* TO '使用者名'@'IP'

         grant select,insert on *.* TO '使用者名'@'IP'

         revoke select on db1.tb1 from '使用者名'@'IP'
      

  四丶資料表基本

1丶建立表

create table 表名(
        列名   類型   是否可以為空
        列名   類型   是否可以為空
)ENGINE=InnoDB DEFAULT CHARSET=utf8
      
是否可以為空,null表示空,非字元串
                  not  null        -    不可空
                  null               -     可空
      
預設值,建立清單示可以指定預設值,當插入資料時如果未主動設定,則自動添加預設值                       create table tbl(
                                    nid int not null defalut 2,
                                    num int not null
         
                          )
      
自增,如果為某列設定自增列,插入資料時無需設定此列,預設将自增(表中隻能有一個自增列)
                    create table tbl(
                                nid int not null auto_increment primary key,                    
                                num int null

                     )
                     或
                    create table tbl(
                                nid int not null auto_increment,
                                num int null,
                                index(nid)
                     )
                     注意:1,對于自增列,必須是索引(含主鍵)
                              2,對于自增可以設定步長和起始值
                                
                                  show session variables like 'auto_inc%';
                                  set session auto_increment_increment=2;
                                  set session auto_increment_offset=10;
 
                                  show global variables like 'quto_inc%';
                                  set global auto_increment_increment=2;
                                  set global auto_increment_offset=10;
      
主鍵,一種特殊的唯一索引,不允許有空值,如果主鍵使用單個列,則它的值必須唯一,如果是多列,則其組合必須唯一·

        create table tbl(
                  nid int not null auto_increment primary key,
                  num int null     
         )
         或 
         create table tbl(
                nid int not null,
                num int not null,
                primary key(nid,num)
         )      
外鍵,一個特殊的索引,隻能是指定内容
             creat table  color(
                      nid int not null primary key,
                      name char(16) not null
              )
 
             create table fruit(
                      nid int not null primary key,
                      smt char(32) null,
                      color_id int not null,
                      constraint fk_cc foreign key (color_id) refences color(nid)
              )

           
      

2丶删除表

    drop  table   表名

3丶清空表

           delete from 表名

           truncate table  表名

4丶修改表

  添加列:alter table 表名 modify column 列名 類型;

     删除列:alter table 表名 drop column 列名

     修改列:

      alter table 表名 modify  column 列名 類型;   ---類型

      alter  table 表名 change 原列名 新列名 類型;  -- 列名,類型

  添加主鍵:

     alter table 表名 add primary key(列名);

  删除主鍵:

     alter table 表名 drop primary key;

     alter table 表名 modify 列名 int, drop primary key;

  添加外鍵:alter table 從表 add constaint 外鍵名稱(形如:FK_從表_主表) foreign key (外鍵字段) references 主表(主鍵字段);

  删除外鍵:alter table 表名 drop foreign key 外鍵名稱

  修改預設值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 10000;

  删除預設值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

5丶基本資料類型

MySQL的資料類型大緻分為:數值,時間和字元串

bit[(M)]
            二進制位(101001),m表示二進制位的長度(1-64),預設m=1

        tinyint[(m)] [unsigned] [zerofill]

            小整數,資料類型用于儲存一些範圍的整數數值範圍:
            有符号:
                -128 ~ 127.
            無符号:
                0 ~ 255

            特别的: MySQL中無布爾值,使用tinyint(1)構造。

        int[(m)][unsigned][zerofill]

            整數,資料類型用于儲存一些範圍的整數數值範圍:
                有符号:
                    -2147483648 ~ 2147483647
                無符号:
                    0 ~ 4294967295

            特别的:整數類型中的m僅用于顯示,對存儲範圍無限制。例如: int(5),當插入資料2時,select 時資料顯示為: 00002

        bigint[(m)][unsigned][zerofill]
            大整數,資料類型用于儲存一些範圍的整數數值範圍:
                有符号:
                    -9223372036854775808 ~ 9223372036854775807
                無符号:
                    0  ~  18446744073709551615

        decimal[(m[,d])] [unsigned] [zerofill]
            準确的小數值,m是數字總個數(負号不算),d是小數點後個數。 m最大值為65,d最大值為30。

            特别的:對于精确數值計算時需要用此類型
                   decaimal能夠存儲精确值的原因在于其内部按照字元串存儲。

        FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]
            單精度浮點數(非準确小數值),m是數字總個數,d是小數點後個數。
                無符号:
                    -3.402823466E+38 to -1.175494351E-38,
                    0
                    1.175494351E-38 to 3.402823466E+38
                有符号:
                    0
                    1.175494351E-38 to 3.402823466E+38

            **** 數值越大,越不準确 ****

        DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]
            雙精度浮點數(非準确小數值),m是數字總個數,d是小數點後個數。

                無符号:
                    -1.7976931348623157E+308 to -2.2250738585072014E-308
                    0
                    2.2250738585072014E-308 to 1.7976931348623157E+308
                有符号:
                    0
                    2.2250738585072014E-308 to 1.7976931348623157E+308
            **** 數值越大,越不準确 ****


        char (m)
            char資料類型用于表示固定長度的字元串,可以包含最多達255個字元。其中m代表字元串的長度。
            PS: 即使資料小于m長度,也會占用m長度
        varchar(m)
            varchars資料類型用于變長的字元串,可以包含最多達255個字元。其中m代表該資料類型所允許儲存的字元串的最大長度,隻要長度小于該最大值的字元串都可以被儲存在該資料類型中。

            注:雖然varchar使用起來較為靈活,但是從整個系統的性能角度來說,char資料類型的處理速度更快,有時甚至可以超出varchar處理速度的50%。是以,使用者在設計資料庫時應當綜合考慮各方面的因素,以求達到最佳的平衡

        text
            text資料類型用于儲存變長的大字元串,可以組多到65535 (2**16 − 1)個字元。

        mediumtext
            A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters.

        longtext
            A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1) characters.


        enum
            枚舉類型,
            An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.)
            示例:
                CREATE TABLE shirts (
                    name VARCHAR(40),
                    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
                );
                INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),('polo shirt','small');

        set
            集合類型
            A SET column can have a maximum of 64 distinct members.
            示例:
                CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));
                INSERT INTO myset (col) VALUES ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d');

        DATE
            YYYY-MM-DD(1000-01-01/9999-12-31)

        TIME
            HH:MM:SS('-838:59:59'/'838:59:59')

        YEAR
            YYYY(1901/2155)

        DATETIME

            YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59    Y)

        TIMESTAMP

            YYYYMMDD HHMMSS(1970-01-01 00:00:00/2037 年某時)
      

  ·更多參考

        http://dev.mysql.com/doc/refman/5.7/en/data-type-overview.html

      http://www.runoob.com/mysql/mysql-data-types.html

 五丶表内容操作

1丶增

insert into 表 (列名,列名...) values (值,值,值...)
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 表
      

2丶删

delete from 表
delete from 表 where id=1 and name='alex'
      

3丶改

update 表 set name = 'alex' where id>1
      

4丶查

select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1
      

5丶其他

MySQL[一]
MySQL[一]
a、條件
    select * from 表 where id > 1 and name != 'alex' and num = 12;
 
    select * from 表 where id between 5 and 16;
 
    select * from 表 where id in (11,22,33)
    select * from 表 where id not in (11,22,33)
    select * from 表 where id in (select nid from 表)
 
b、通配符
    select * from 表 where name like 'ale%'  - ale開頭的所有(多個字元串)
    select * from 表 where name like 'ale_'  - ale開頭的所有(一個字元)
 
c、限制
    select * from 表 limit 5;            - 前5行
    select * from 表 limit 4,5;          - 從第4行開始的5行
    select * from 表 limit 5 offset 4    - 從第4行開始的5行
 
d、排序
    select * from 表 order by 列 asc              - 根據 “列” 從小到大排列
    select * from 表 order by 列 desc             - 根據 “列” 從大到小排列
    select * from 表 order by 列1 desc,列2 asc    - 根據 “列1” 從大到小排列,如果相同則按列2從小到大排序
 
e、分組
    select num from 表 group by num
    select num,nid from 表 group by num,nid
    select num,nid from 表  where nid > 10 group by num,nid order nid desc
    select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
 
    select num from 表 group by num having max(id) > 10
 
    特别的:group by 必須在where之後,order by之前
 
f、連表
    無對應關系則不顯示
    select A.num, A.name, B.name
    from A,B
    Where A.nid = B.nid
 
    無對應關系則不顯示
    select A.num, A.name, B.name
    from A inner join B
    on A.nid = B.nid
 
    A表所有顯示,如果B中無對應關系,則值為null
    select A.num, A.name, B.name
    from A left join B
    on A.nid = B.nid
 
    B表所有顯示,如果B中無對應關系,則值為null
    select A.num, A.name, B.name
    from A right join B
    on A.nid = B.nid
 
g、組合
    組合,自動處理重合
    select nickname
    from A
    union
    select name
    from B
 
    組合,不處理重合
    select nickname
    from A
    union all
    select name
    from B      

View Code