mysq基礎

1、概念

 數據庫,文件夾

    數據庫表,文件

    數據行,文件中的一行數據

2、初始:

show databases;    #查看當前Mysql都有哪些數據,根目錄都有哪些文件夾

create database 數據庫名;創建文件夾

use 數據庫名;使用選用的數據庫,進入目錄

show tables; 查看當前數據庫下都有哪些表

create table 表名(nid int,name varchar(20));  #創建數據庫表

select * from 表名;  #查看錶中的所有數據

insert to 表明(nid,name) values(1,'davide',,'123')

3、授權以及創建用戶

mysql> select Host,User from user;

+-----------+---------------+

| Host      | User          |

+-----------+---------------+

| localhost | mysql.session |

| localhost | mysql.sys    |

| localhost | root          |

+-----------+---------------+

3 rows in set (0.00 sec)

用戶管理特殊命令:

創建用戶

create user  '用戶名' @ 'IP地址' identified by  '密碼' ;

刪除用戶

drop user  '用戶名' @ 'IP地址' ;

修改用戶

rename user  '用戶名' @ 'IP地址' ; to  '新用戶名' @ 'IP地址' ;;

修改密碼

set password  for '用戶名' @ 'IP地址' = Password( '新密碼' )

PS:用戶權限相關數據保存在mysql數據庫的user表中,所以也可以直接對其進行操作(不建議)

創建一個用戶

mysql> create user xiaohu@localhost identified by '123';

Query OK, 0 rows affected (0.01 sec)

mysql> select Host,User from user;

+-----------+---------------+

| Host      | User          |

+-----------+---------------+

| localhost | mysql.session |

| localhost | mysql.sys    |

| localhost | root          |

| localhost | xiaohu        |

+-----------+---------------+

4 rows in set (0.00 sec)

刪除一個用戶

mysql> drop user xiaohu@localhost;

Query OK, 0 rows affected (0.00 sec)

更改名字

mysql> rename user davide@localhost to [email protected];

Query OK, 0 rows affected (0.00 sec)

mysql> select Host,User from user;

+-----------+---------------+

| Host      | User          |

+-----------+---------------+

| 127.0.0.1 | eric          |

| localhost | mysql.session |

| localhost | mysql.sys    |

| localhost | root          |

+-----------+---------------+

4 rows in set (0.00 sec)

給用戶設置密碼

mysql> set password for root@localhost = Password('6666');

Query OK, 0 rows affected, 1 warning (0.00 sec)

登錄失敗 默認登錄的指定的是localhost

C:\Users\Administrator>mysql -u eric -p

Enter password: ***

ERROR 1045 (28000): Access denied for user 'eric'@'localhost' (using password: YES)

使用-h指定登錄的主機

C:\Users\Administrator>mysql -u eric -h 127.0.0.1 -p

Enter password: ***

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 7

Server version: 5.7.23 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

5、權限、

默認什麼都沒有

show grants for '用戶'@'IP地址' -- 查看權限

grant  權限 on 數據庫.表 to    '用戶' @ 'IP地址' -- 授權

revoke 權限 on 數據庫.表 from  '用戶' @ 'IP地址' -- 取消權限

select,查

數據庫.表

      test.tb1

      test.*  數據庫test下的所有表

      *.*      所有的庫和所有的表

                 小虎@localhost

權限:

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、rename user和revoke  all privileges

create view            使用create view

delete                  使用delete

drop                    使用drop table

execute                使用call和存儲過程

file                    使用select into 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 view              使用show view

update                  使用update

reload                  使用flush

shutdown                使用mysqladmin shutdown(關閉MySQL)

super                  使用change master、kill、logs、purge、master和set global。還允許mysqladmin調試登陸

replication client      服務器位置的訪問

replication slave      由複製從屬使用

用戶名@IP地址

            用戶只能在改IP下才能訪問

            用戶名@192.168.1.%  用戶只能在改IP段下才能訪問(通配符%表示任意)

            用戶名@%            用戶可以再任意IP下訪問(默認IP地址爲%)

#清空表的內容#清空表的內容#清空表的內容#清空表的內容忘記密碼

# 啓動免授權服務端

mysqld --skip-grant-tables

# 客戶端

mysql -u root -p

# 修改用戶名密碼

update mysql.user set authentication_string=password('666') where user='root';

flush privileges;

######################總結:

a.解放說收,在重複操作文件,直接將命令發送給mysql服務器,自動操作

b.數據庫表

c.創建用戶和授權

  密碼:必須用

  其他:推薦用

d.客戶端連接MySQL提供客戶端

  1.mysql -u root -h 192.168.1.1 -P 3306

4、SQL語句

a、數據庫級別

show databases;查看當前數據庫

create databases 數據庫名稱;

CREATE DATABASE 數據庫名稱 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

use 數據庫名稱;進入數據庫

drop  database 數據庫名稱

b、表級別

show tables;查看當前數據庫有哪些表

desc 表名;

########create tables 表名(nid int,name varchar2(20));

#事務,原子性操作,回滾

a、默認值

b、是否可以爲空

c、自增列(一張表只能有一個,必須是索引-主鍵)

d、主鍵

一張表只能有一個主鍵,唯一不能重複,不能爲空。一般情況下自增列設置成主鍵

唯一索引:

可以爲null,一張表可以有多個唯一列

----約束

----索引,加速查找

create table student(

        name varchar2(20) not null,

        num int not null,

        age int,

        gender int,

        primary key (name,num)

)

create table tb5(

        nid int not null auto_increment primary key,

        name varchar2(20),

        age int defualt 19

        )engine=innodb default charset=utf8;

約束:

                            name num  age

      a  88  9

       a  99  9

#主鍵:

      不能爲null,

      不能重複,

      一張表只有一個主鍵(可以多列組成主鍵)

#一般用法:

        nid int auto_increment primary key

        drop table 表名; 刪除表

        delete from 表名;#清空表的內容

        truncate table 表名  #清空表內容,性能高速度快,刪除自增

select * from 表名;查看錶的內容

e:外鍵:foreign key,一對多

  兩張表建立約束,

      -----約束

    -----foreign key,一對多

mysql> alter table userinfo add constraint fk_u_p foreign key userinfo(part_nid) references part(nid);

      數據行級別

select * from tb1;

insert into tb1(name,age) values('joy',19);

insert into tb1(name.age) values('davide',19),('jolin',18)#插入多條數據

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

insert into tb31(name,age) select caption,gender from tb32;

delete from 表

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

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

select * from 表

select * from 表 where id > 1

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

MySQL的數據類型大致分爲:數值、時間和字符串f:數據類型:

5、其他

連表操作:

#連表

select * from a,b where a.x = b.x;

#left join

select * from a left join b on a.x = b.x;

#inner join    #永遠不會出現NULL

select * from part inner join userinfo on userinfo.part_nid = part.nid;

a、條件

    select * from 表 where id > 1 and name != 'davide' 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

mysql> select part_nid,count(nid) from userinfo group by part_nid;

+----------+------------+

| part_nid | count(nid) |

+----------+------------+

|        1 |          2 |

|        2 |          3 |

|        4 |          1 |

+----------+------------+

mysql> select part_nid as a,count(nid) as b from userinfo group by part_nid;##起一個別名

+------+---+

| a    | b |

+------+---+

|    1 | 2 |

|    2 | 3 |

|    4 | 1 |

+------+---+

mysql> select part_nid as a,count(nid) as b from userinfo group by part_nid having count(nid)>1;###對聚合函數適應having進行篩選

+------+---+

| a    | b |

+------+---+

|    1 | 2 |

|    2 | 3 |

+------+---+

2 rows in set (0.00 sec)

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

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 年某時

1、創建表

create table 表名(

    列名  類型  是否可以爲空,

    列名  類型  是否可以爲空

)ENGINE=InnoDB DEFAULT CHARSET=utf8

        是否可空,null表示空,非字符串

            not null    - 不可空

            null        - 可空

        默認值,創建列時可以指定默認值,當插入數據時如果未主動設置,則自動添加默認值

            create table tb1(

                nid int not null defalut 2,

                num int not null

            )

      自增,如果爲某列設置自增列,插入數據時無需設置此列,默認將自增(表中只能有一個自增列)

            create table tb1(

                nid int not null auto_increment primary key,

                num int null

            )

            或

            create table tb1(

                nid int not null auto_increment,

                num int null,

                index(nid)

            )

            注意:1、對於自增列,必須是索引(含主鍵)。

Mysql常見的索引有:

a、普通索引

b、唯一索引

c、主鍵索引

d、組合索引

a、普通索引唯一的一個功能是:加速查找

創建表+索引

mysql> create table tb21(
     -> nid int not null auto_increment primary key,
     -> name varchar(32) not null,
     -> email varchar(64) not null,
     -> extra text,
     -> index ix_name(name))engine=innodb default charset=utf8;
Query OK, 0 rows affected (0.53 sec)

創建普通索引;

create unique index 索引名 on 表名(列名)


刪除普通索引

drop index index_name on table_name;


查看索引

show index from table_name;

b、唯一索引

唯一索引有兩個功能;加速查找和唯一約束(可含null)

mysql> create table tb21(
    -> nid int not null auto_increment primary key,
    -> name varchar(32) not null,
     -> email varchar(64) not null,
     -> extra text,
     ->unique index ix_name(name))engine=innodb default charset=utf8;

創建唯一索引

create unique index 索引名 on 表名(列名)

刪除唯一索引

drop unique index index_name on table_name;

c、主鍵索引有兩個功能:加速查詢和唯一約束(不可含null)

創建表和主鍵索引

mysql> create table tb22(
     -> nid int not null auto_increment primary key,
     -> name varchar(32) not null,
     -> email varchar(64) not null,
     -> extra text,
     -> index ix_name(name))engine=innodb default charset=utf8;

創建主鍵索引

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

刪除主鍵索引(如果一個主鍵的,不能直接刪除該列的主鍵索引,應該先取消自增長,在刪除主鍵的特性)

mysql> alter table tb22 modify nid int;
Query OK, 0 rows affected (0.73 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table tb22 drop primary key;
Query OK, 0 rows affected (0.83 sec)
Records: 0  Duplicates: 0  Warnings: 0

d、組合索引

組合索引是將N個列組合成一個索引.(1、分爲普通組合索引,沒有約束和unique組合索引,兩列數據同時都不相同時才能插入,不然報錯)

查找過程中實行最左匹配,如果不選擇最左索引值,就不走索引。

創建表

mysql> create table tb22(
    -> nid int not null auto_increment primary key,
    -> name varchar(32) not null,
     -> email varchar(64) not null,
     -> extra text,
     -> index ix_name(name))engine=innodb default charset=utf8;

創建組合索引

create index ix_name_email on tb22(name,email);


2、對於自增可以設置步長和起始值

       show session variables like 'auto_inc%';

       set session auto_increment_increment=2;

       set session auto_increment_offset=10;

       shwo global  variables like 'auto_inc%';

       set global auto_increment_increment=2;

      set global auto_increment_offset=10;

       主鍵,一種特殊的唯一索引,不允許有空值,如果主鍵使用單個列,則它的值必須唯一,如果是多列,則其組合必須唯一。

            create table tb1(

                nid int not null auto_increment primary key,

                num int null

            )

            或

            create table tb1(

                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) references color(nid)

            )

2、刪除表

drop table 表名

3、清空表

delete from 表名

truncate table 表名

4、修改表

添加列:alter table 表名 add 列名 類型

刪除列: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 constraint 外鍵名稱(形如:FK_從表_主表) foreign key 從表(外鍵字段) references 主表(主鍵字段);

mysql> alter table userinfo add constraint fk_u_p foreign key userinfo(part_nid) references part(nid);

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

修改默認值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;

刪除默認值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

#第三行開始取4行修改表

添加列:alter table 表名 add 列名 類型

刪除列: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 constraint 外鍵名稱(形如:FK_從表_主表) foreign key 從表(外鍵字段) references 主表(主鍵字段);

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

修改默認值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;

刪除默認值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

####總結##########################################

1、數據庫概念

2、數據庫、表、行

3、啓動服務器端,啓動客戶端連接服務器

  用戶管理

  權限管理

4、SQL語句

數據庫操作

表操作

    是否可以爲空

    默認值

    主鍵

    外鍵

    自增

 數據類型

數據行操作

    增

    刪

    改

 查

其他

    limit offset

    left join

    order by

    group by,having

聚合函數

max mix sun count

分頁

前幾行,select   .....limit3;

limit 3,4      #第三行開始取4行

limit 4 offset 3#第三行開始取4行

連表

left join on

#表1 left join 表2 on

#如果表1中的數據多,表2少,null補充

right join

inner join

#如果表1中數據多,表2少,null不顯示

排序

desc

asc注意:對於同時搜索n個條件時,組合索引的性能好於多個單一索引合併

nid    name

1  davide

2  eric

3      davide

4      davide

從小到達,id從大到小

select * from tb1 order by name asc,nid desc;

聯合

union

union all

條件:> < = !=

in(1,2,3,4)

not in (.....)

in(select nid from userinfo)

連表,外鍵

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章