MySQL基礎(一):基本操作


一、下載安裝及連接

MySQL是一個關系型數據庫管理系統,由瑞典MySQL AB 公司開發,目前屬於 Oracle 旗下公司。MySQL 最流行的關系型數據庫管理系統,在 WEB 應用方面MySQL是最好的 RDBMS (Relational Database Management System,關系數據庫管理系統) 應用軟件之一。

windows版本

1. 下載

http://dev.mysql.com/downloads/mysql/

2.安裝及初始化

本文以windows下.zip安裝包為例,解壓到任意目錄后執行:

此處需要在C:\mysql-5.7.20-winx64下手動創建個data目錄,否則可能會報錯。

cd C:\mysql-5.7.20-winx64\bin
mysqld --initialize-insecure

3. 啟動MySQL服務

方式一:每次手動啟動mysql服務。

cd C:\mysql-5.7.20-winx64\bin
mysqld
方式二:將mysqld制作成服務,然后每次自動啟動。
"c:\mysql-5.7.20-winx64\bin\mysqld" --install
  net start mysql
  net stop mysql

4.cmd下連接
C:\mysql-5.7.20-winx64\mysql-5.7.20-winx64\mysql -u root -p

默認root密碼為空。

如果遠程連接:mysql -u root -h 192.168.1.1 -p

image

二、數據庫級別常用SQL語句

1. 入門級常用語句匯總(更新中)

show databases;                # 查看當前Mysql都有那些數據,根目錄都有那些文件夾
      
create database 數據庫名;   # 創建數據庫文件夾


use 數據庫名;               # 使用選中數據庫,進入目錄
            
show tables;                # 查看當前數據庫下都有那些表,
            
create table 表名(nid int,name varchar(20), pwd varchar(64)); # 創建數據庫表

drop table 表名                  # 刪除整個表
delete from 表名               # 刪除表中的數據,保留表結構,可恢復
truncae table 表名          # 以更快的方式刪除表中的數據,不可恢復。

desc 標明                     #查看描述
            
  select * from 表名;       # 查看表中的所有數據
            
  insert into 表名(nid,name,pwd) values(1,'alex','123');  # 插入數據

alter table user_info add constraint fk_u_p foreign key user_info(part_nid) references part(nid);  # 創建外鍵關聯,下面有另一種方式(子表創建時就關聯外鍵)

# 連表
select * form a,b where a.x = b.o

# join,
     a. left join
         select * from a LEFT OUTER JOIN b ON a.x = b.o

     b. inner join ,永遠不會出現Null
         select * from a inner JOIN b ON a.x = b.o

select part_nid as a, count(nid) as b from userinfo group by part_nid;

2. 用戶管理

        創建用戶
             create user '用戶名'@'IP地址' identified by '密碼';
         刪除用戶
             drop user '用戶名'@'IP地址';
         修改用戶
             rename user '用戶名'@'IP地址'; to '新用戶名'@'IP地址';;
         修改密碼
             set password for '用戶名'@'IP地址' = Password('新密碼')
            
         PS:用戶權限相關數據保存在mysql數據庫的user表中,所以也可以直接對其進行操作(不建議)
         select User,Host,password_expired from user;


# 啟動免授權服務端
mysqld --skip-grant-tables

# 客戶端
mysql -u root -p

# 修改用戶名密碼
update mysql.user set authentication_string=password('666') where user='root';
flush privileges;

忘記密碼
忘記密碼

3. 授權管理

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

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

GRANT SELECT ON `test`.`t1` TO 'lyy'@'%'

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、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地址為%)
用戶和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'

示例
授權示例

flush privileges,將數據讀取到內存中,從而立即生效。

三、數據表級別常用SQL語句

1. 創建表

  create table tb5(
    nid int not null auto_increment primary key,
   name varchar(16),
   age int default 19
   )engine=innodb default charset=utf8;
 

注釋:

primary-key //創建主鍵,為了加速查找。主鍵在表中唯一且不可重復、不能為null。

auto-increment//設為自增列,一個表中只能有一個自增列

default  //是設置默認值   update userinfo set part_nid=2;

engine=innodb //設置存儲引擎

說明:

MyISAM 和InnoDB是最常用的兩個mysql數據庫引擎,主要區別援引如下:

1. InnoDB支持事務,MyISAM不支持,對於InnoDB每一條SQL語言都默認封裝成事務,自動提交,這樣會影響速度,所以最好把多條SQL語言放在begin和commit之間,組成一個事務;


2. InnoDB支持外鍵,而MyISAM不支持。對一個包含外鍵的InnoDB表轉為MYISAM會失敗;


3. InnoDB是聚集索引,數據文件是和索引綁在一起的,必須要有主鍵,通過主鍵索引效率很高。但是輔助索引需要兩次查詢,先查詢到主鍵,然后再通過主鍵查詢到數據。因此,主鍵不應該過大,因為主鍵太大,其他索引也都會很大。而MyISAM是非聚集索引,數據文件是分離的,索引保存的是數據文件的指針。主鍵索引和輔助索引是獨立的。


4. InnoDB不保存表的具體行數,執行select count(*) from table時需要全表掃描。而MyISAM用一個變量保存了整個表的行數,執行上述語句時只需要讀出該變量即可,速度很快;


5. Innodb不支持全文索引,而MyISAM支持全文索引,查詢效率上MyISAM要高;


如何選擇:

1. 是否要支持事務,如果要請選擇innodb,如果不需要可以考慮MyISAM;

2. 如果表中絕大多數都只是讀查詢,可以考慮MyISAM,如果既有讀寫也挺頻繁,請使用InnoDB。

3. 系統奔潰后,MyISAM恢復起來更困難,能否接受;

4. MySQL5.5版本開始Innodb已經成為Mysql的默認引擎(之前是MyISAM),說明其優勢是有目共睹的,如果你不知道用什么,那就用InnoDB,至少不會差。


作者:Oscarwin
鏈接:https://www.zhihu.com/question/20596402/answer/211492971
來源:知乎

簡單總結:

1、myisam查詢效率更高,支持全文索引。innodb不支持全文索引,查詢效率差myisam6-7倍。

2、innodb支持事務,行鎖,外鍵。myisam不支持。

如果數據表涉及的存儲數據多、查詢多,用myisam,如文章表。如果數據表涉及業務邏輯多,增刪改操作多,就用innodb,如訂單表。

作者:陳志遠
鏈接:https://www.zhihu.com/question/20596402/answer/200001639
來源:知乎

自增,如果為某列設置自增列,插入數據時無需設置此列,默認將自增(表中只能有一個自增列)
            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、對於自增列,必須是索引(含主鍵)。
                 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)
            )
外鍵

alter table user_info add constraint fk_u_p foreign key user_info(part_nid) references part(nid);

外鍵的作用有二:

1. 軟件工程的模塊化思想,一張表不宜過大;

2. 可以用主表(這里也叫外表,主鍵表)來約束從表(外鍵表);比如主表設置一個學號,子表的外鍵的學號字段就只能在這個范圍內輸入;

外鍵說明:

對於從表來說,外鍵不一定需要作為從表的主鍵,外鍵也不一定是外表的主鍵,外表的唯一鍵就可以作 為從表的外鍵。

2.  表內容操作

1. 增

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

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

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

2. 刪

delete from

delete from where id=1 and name'jack’


drop table表名 //整表刪除

truncae table 表名 //整表刪除

3. 改

update set name 'jack' where id>1  (修改表內容)

表本身的修改:

添加列: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;


4. 查

select * from

select * from where id > 1

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

更多查詢操作(更新中)

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

select part_nid as a, count(nid) as b from userinfo group by part_nid;

3. MySQL基本數據類型

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

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

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

            小整數,數據類型用於保存一些范圍的整數數值范圍:
            有符號:
                -128 ~ 127.
            無符號:
~ 255

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

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

            整數,數據類型用於保存一些范圍的整數數值范圍:
                有符號:
                    -2147483648 ~ 2147483647
                無符號:
~ 4294967295

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

        bigint[(m)][unsigned][zerofill]
            大整數,數據類型用於保存一些范圍的整數數值范圍:
                有符號:
                    -9223372036854775808 ~ 9223372036854775807
                無符號:
 ~  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,
                    1.175494351E-38 to 3.402823466E+38
                有符號:
                    1.175494351E-38 to 3.402823466E+38

            **** 數值越大,越不准確 ****

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

                無符號:
                    -1.7976931348623157E+308 to -2.2250738585072014E-308
                    2.2250738585072014E-308 to 1.7976931348623157E+308
                有符號:
                    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 年某時)
數值類型詳細

二進制數據:TinyBlob、Blob、MediumBlob、LongBlob

更多參考:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM