msql數據庫基礎


一、數據庫操作

1、顯示數據庫

SHOW DATABASES;
SHOW CREATE DATABASE 數據庫名稱; #數據庫的創建信息

2、創建數據庫

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

#gbk
CREATE DATABASE 數據庫名稱 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;

數據庫命名規則

1、可以由字母、數字、下划線、@、#、$組成
2、區分大小寫
3、唯一性
4、不能使用關鍵字如 create等
5、不能單獨使用數字
6、最長128位

3、使用數據庫

USE 數據庫名

4、修改數據庫

ALTER DATABASE 數據庫名 CHARSET utf8;

5、刪除數據庫

DROP DATABASE 數據庫名;

6、用戶管理

用戶相關信息是放在mysql數據庫中的user表中,所以對用戶的操作,實際上就是對user表的操作。

#創建用戶
    create user '用戶名'@'IP地址' identified by '密碼';
#刪除用戶
    drop user '用戶名'@'IP地址';
#修改用戶
    rename user '用戶名'@'IP地址'; to '新用戶名'@'IP地址';;
#修改密碼
    set password for '用戶名'@'IP地址' = Password('新密碼')

例如:

mysql> create user 'xiaohua'@'localhost' identified by '12345678hr';

7、授權管理

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

例如:

mysql> show grants for 'root'@'127.0.0.1';
#賦予權限
grant  權限 on 數據庫.表 to '用戶'@'IP地址'

例如:

mysql> grant select on test_study.*  to 'xiaohu'@'localhost';
#取消權限
revoke 權限 on 數據庫.表 from '用戶'@'IP地址'      #如果權限不存在會報錯

例如:

mysql> revoke select on test_study.*  from 'xiaohu'@'localhost';

在賦予權限時,也可以同時賦予多個權限,中間以逗號隔開:

mysql> grant select,update,delete,insert on test_study.* to 'xiaohu'@'localhost';

更改后的權限立即生效,使用:

flush  privileges ;

設置權限的語句中應包含以下信息:

  • 要授予的權限(例如select、update、delete、insert)
  • 被授予訪問權限的數據庫或表
  • 用戶信息

權限設置的層次:

  • 整個服務器,使用 grant  all  和revoke all...*.*
 grant all privileges on *.* TO '用戶名'@'IP'
  • 整個數據庫,使用on  database.*
 grant select on db_test.* TO '用戶名'@'IP'
  • 某張表,使用on  database.table
revoke select on db1.tb1 from '用戶名'@'IP'
  • 某一列或多列
grant select(id, name) on db1.tb1 to 'xiaohu'@'localhost';
  • 存儲過程
grant execute on procedure dbtest.pro_remo to ’xiaohu’@’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       由復制從屬使用

對於權限
權限設置
            數據庫名.*           數據庫中的所有
            數據庫名.表          指定數據庫中的某張表
            數據庫名.存儲過程     指定數據庫中的存儲過程
            *.*                所有數據庫
數據庫設置

參考:https://www.cnblogs.com/wupeiqi/articles/5713315.html

二、表操作

 1、創建表

CREATE TABLE 表名 (
字段名1  數據類型  字段選項 ,
字段名2  數據類型  字段選項 (無逗號)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

說明:

  •  如果表指定了字符集和校對規則,則以表指定的為准,如果表沒有指定,則以表所在的數據庫的字符集和校對規則。
  • engin 就是存儲引擎,比如常用的(MyISAM、InnoDB, Memory), 如果創建表的時指定了這個存儲引擎,則以這個准,如果沒有指定以默認的. 在my.ini中設置的有。
  • 加上auto_increment,主鍵自動增長
  • 可以通過constraint 指定外鍵
CREATE TABLE `userinfo`
     (
         `nid` int unsigned AUTO_INCREMENT PRIMARY KEY COMMENT "主鍵ID",
         `name` varchar(64) NOT NULL COMMENT "姓名",
         `nickname` varchar(64) NOT NULL DEFAULT "" COMMENT "昵稱",
         `password` char(32) NOT NULL COMMENT "密碼" )CHARSET=UTF8 COLLATE=utf8_general_ci ENGINE=InnoDB;

2、查看表結構

desc 表名;
describe 表名;

3、刪除表

drop table 表名

4、清空表

delete from 表名
truncate table 表名

它們都是默認刪除表內容,但是truncate 的刪除速度更快

5、修改表

修改表名: alter table 表名 rename 新表名;

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

三、表內容操作

#增加記錄
insert into 表 (列名,列名...) values (值,值,值...)
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from#修改記錄
update 表 set name = 'xxx' 
update 表 set name = 'xxx' where id>1

#刪除記錄
delete from 表
delete from 表 where id=1 and name='xxx'

#查詢記錄
select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id = 1

四、表記錄查詢

-- 查詢表達式

   SELECT *|field1,filed2 ...   FROM tab_name
                  WHERE 條件
                  GROUP BY field
                  HAVING 篩選
                  ORDER BY field
                  LIMIT 限制條數

--向userinfo表插入數據
  INSERT INTO userinfo VALUES  (1,"張明","明",123),
(2,"李二","二",456),
(3,"王五","五",789),
(4,"順六","六",888),
(5,"小七","七",100);

--使用where子句,進行過濾查詢
  #查詢nid>2的記錄
  select * from userinfo where nid>2;

  #查詢nid在[2,4]的記錄
  select * from userinfo where nid between 2 and 4;
  
  #查詢nid=2,3,4的記錄
  select * from userinfo where nid in (2,3,4);

  #查詢nid != 2,3
  select * from userinfo where nid not in (2,3);
  #nid是另一張變的id或者其它關聯的數據
  select * from userinfo where nid in (select user_id from depart);

--使用通配符
  #匹配以bg開頭多個字符
  select * from userinfo where nickname like 'bg%';
  #匹配以bg開頭一個字符
  select * from userinfo where nickname like 'bg_';

--限制limit
  #取出表的前兩行
  select * from userinfo limit 2;
  
  #從第二行開始的后兩行
  select * from userinfo limit 2,2;

  #從第一行開始的后三行
  select * from userinfo limit 3 offset 1;

--排序order by
  #根據nid列從小到大排列
  select * from userinfo order by nid;
  
  #根據nid列從大到小排列
  select * from userinfo order by nid desc;
  
  根據name列從大到小排列,如果相同則按nid列從小到大排序
  select * from userinfo order by name desc,nid asc;

--分組group by
#建測試數據庫
create table book_info(id int primary key auto_increment,
                        book_name varchar(20),
                         price float(6,2),
                        description varchar(20),
                        pub_date date
                        );

#插入數據                                                
insert into book_info (book_name,price,description,pub_date) values ("python",20,"jfjd",20180304),
                                                                    ("python",40,"hhjhj",20190304),
                                                                    ("java",80,"lkkj",20180404),
                                                                    ("c",20,"lkk",20180409),
                                                                    ("python",60,"hhjj",20190404),
                                                                    ("java",20,"jfjd",20180304);
#按位置字段進行分組篩選
select * from book_info group by 2;#按第二列進行分組

 #按字段名分組后顯示內容

  select * from book_info group by book_name;

         

  

 #group by 中使用where以及order by語句

  select id,book_name,price from book_info where id>1 group by book_name order by price desc;

         

  

 #group by 中使用聚合函數

   select book_name,sum(price) from book_info group by book_name; #將每一個種類的書籍的總價求出來

     

  

  select book_name,count(*),max(price),min(price),avg(price) from book_info group by book_name;#求出分組后每一種類書籍的個數、價格的最大值、最小值、平均值

      

  

  #group by中使用having語句

   select * from book_info having id > 2; #此時相當於select * from book_info where id > 2; 

   select id,book_name,price from book_info group by book_name having min(id) > 3; #對書籍通過名字進行分組,分組后選出id至少大於3的組別

  

           

   having 和 where兩者都可以對查詢結果進行進一步的過濾,差別有:
          <1>where語句只能用在分組之前的篩選,having可以用在分組之后的篩選;
          <2>使用where語句的地方都可以用having進行替換
          <3>having中可以用聚合函數,where中不行。

  注意:group by必須在where之后order by之前

-- group_concat
() 函數
 將group by產生的同一個分組中的值連接起來,返回一個字符串結果。
 

  可以看到分組后price的值只有一個,如何將同一種類的所有price嫻熟出來呢?

  select id,book_name,group_concat(price) from book_info group by book_name;

  

  --使用正則表達式

   select * from book_info where book_name regexp '^j';#以‘j’字符開頭

  

  select * from book_info where book_name regexp '[th]';#字符集合。匹配所包含的任意一個字符

  

 更多請參考:https://www.runoob.com/mysql/mysql-regexp.html

五、連表查詢

1、測試數據准備

create table User(
  id int primary key auto_increment,
  name varchar (20),
  dept_id int
);
insert into User(name,dept_id) values ("abil",100),
                        ("lily",101),
                        ("cail",102),
                        ("veyr",103),
                        ("pty",104);

create table Dept(
  dept_id int ,
  dept_name varchar (100)
)charset=utf8 collate=utf8_general_ci engine=innodb;

insert into Dept(dept_id, dept_name) values (100,"品質部"),
                        (101,"生產部"),
                        (102,"管理部"),
                        (103,"品質部"),
                        (104,"生產部");

mysql> select * from user;
+----+------+---------+
| id | name | dept_id |
+----+------+---------+
|  1 | abil |     100 |
|  2 | lily |     101 |
|  3 | cail |     102 |
|  4 | veyr |     103 |
|  5 | pty  |     104 |
+----+------+---------+
5 rows in set (0.00 sec)

mysql> select * from dept;
+---------+-----------+
| dept_id | dept_name |
+---------+-----------+
|     100 | 品質部    |
|     101 | 生產部    |
|     102 | 管理部    |
|     103 | 品質部    |
|     104 | 生產部    |
+---------+-----------+
5 rows in set (0.00 sec)

 2、笛卡爾積查詢

如果想一次查出兩張表的內容呢?那么應該如何查詢
mysql> select * from user,dept;
+----+------+---------+---------+-----------+
| id | name | dept_id | dept_id | dept_name |
+----+------+---------+---------+-----------+
| 1 | abil | 100 | 100 | 品質部 |
| 2 | lily | 101 | 100 | 品質部 |
| 3 | cail | 102 | 100 | 品質部 |
| 4 | veyr | 103 | 100 | 品質部 |
| 5 | pty | 104 | 100 | 品質部 |
| 1 | abil | 100 | 101 | 生產部 |
| 2 | lily | 101 | 101 | 生產部 |
| 3 | cail | 102 | 101 | 生產部 |
| 4 | veyr | 103 | 101 | 生產部 |
| 5 | pty | 104 | 101 | 生產部 |
| 1 | abil | 100 | 102 | 管理部 |
| 2 | lily | 101 | 102 | 管理部 |
| 3 | cail | 102 | 102 | 管理部 |
| 4 | veyr | 103 | 102 | 管理部 |
| 5 | pty | 104 | 102 | 管理部 |
| 1 | abil | 100 | 103 | 品質部 |
| 2 | lily | 101 | 103 | 品質部 |
| 3 | cail | 102 | 103 | 品質部 |
| 4 | veyr | 103 | 103 | 品質部 |
| 5 | pty | 104 | 103 | 品質部 |
| 1 | abil | 100 | 104 | 生產部 |
| 2 | lily | 101 | 104 | 生產部 |
| 3 | cail | 102 | 104 | 生產部 |
| 4 | veyr | 103 | 104 | 生產部 |
| 5 | pty | 104 | 104 | 生產部 |
+----+------+---------+---------+-----------+
25 rows in set (0.00 sec)

很明顯上述這樣查詢有很多重復,這就是笛卡爾積。

3、內連接

查詢兩張表都有關聯的數據,相當於利用where語句從笛卡爾積中篩選數據

 select * from user,dept where user.dept_id=dept.dept_id;

 

select * from user inner join dept on user.dept_id=dept.dept_id;

 

4、外連接

  • 外左鏈接

   User表(左)有則顯示,如果Dept表(右)中無對應關系,則值為null

select * from user left join dept on user.dept_id=dept.dept_id;

 

  • 外右連接

  Dept表(有)有則顯示,如果User表(左)中無對應關系,則值為null

 select * from user right join dept on user.dept_id=dept.dept_id;

 

六、組合

  用於連接兩個以上的 SELECT 語句的結果組合到一個結果集合中。多個 SELECT 語句會刪除重復的數據。  

#語法
SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] UNION [ALL
| DISTINCT] SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions];

  實例:

select name from User union select dept_name from dept; #將user表中的name與dept表中的dept_name進行組合

 

注意:union與union all的區別是union會去掉相同的紀錄,而union all不會

 

 更多查看:https://www.runoob.com/mysql/mysql-union-operation.html

七、連表查詢之子查詢

  將一個查詢語句嵌套在另一個查詢語句中

  1、where型子查詢 

select * from user where dept_id in (select dept_id from dept where dept_id>102);

 

  2、from型子查詢:把內層的查詢結果當成臨時表,查詢結果集可以當成表

select distinct id,name,dept_id from (select * from user where id > 2 order by dept_id desc) as u;

 

  3、exists型子查詢:把外層查詢的結果,拿到內層去測試,如果內層的語句成立,返回True,外層查詢語句將進行查詢;當返回值為False時,外層查詢語句不進行查詢

select * from dept where exists (select dept_id from User where dept_id in (101,102));

 

 

 

 

 

 


免責聲明!

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



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