日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

3.表数据的CRUD

發布時間:2024/3/13 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 3.表数据的CRUD 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據的CRUD操作

  • 新增數據
  • 修改數據
  • 刪除數據
  • 查詢數據

MySQL數據的命令不區分大小寫

添加數據 INSERT INTO

  • 方式一 (不推薦)
insert into <tableName> values(val1, val2 , val3 ... ) ;

此操作要求 錄入的 值的數量必須和 表中的字段數量保持完全一致

要求 錄入值的順序 和 表中字段定義的順序 保持一致 (可以使用 DESC 命令查看表結構字段的順序)

在錄入數據的時候,字符串必須用 單引號 引起來

獲取 當前系統時間 ,可以用 now() 函數 ,如果不需要錄入,以 null 來標識即可

上述添加數據的方式不推薦使用

  • 方式二 (推薦且常用)
insert into <tableName>(col1, col2, col3, ....) values(val1, val2, val3, ...) ;insert into t_book(id, price, author, book_name, create_time, status) values(2, 10, '古龍', '小李飛刀', now(), '1');

推薦的寫法

從 插入語句中能夠直觀的看到 要錄入的字段有哪些,可以進行 部分字段值的錄入

字段名在 定義的時候,不需要和數據庫中定義的順序保持一致

值的順序 只需要 和 在 插入命令上的 字段順序保持一致 即可

批量 添加數據

insert into <tableName>(col1, col2, col3, ....) values (val1, val2, val3, .... ), (val1, val2, val3 , ....), (val1, val2, val3, ...), ... ;insert into t_book(id, price, author, book_name, create_time, status) values (3, 30, '辰東', '神墓', now(), '1'), (4, 40, '辰東', '遮天', now(), '1');

簡單查詢數據

select * from <tableName> ; -- 查詢表中所有的數據

修改數據 UPDATE

  • 全表數據進行修改 (不常使用)
update <tableName> set <columnName> = <columnVal> , <columnName> = <columnVal> .... ; -- 表中所有的數據都會被修改-- 將 所有的書籍降價到 80% , 并 重置 更新時間 update t_book set price = price * 0.8 , update_time = now() ;
  • 帶 條件 的數據更新 (常用的操作)
update <tableName> set <columnName> = <columnVal> , <columnName> = <columnVal> .... where 條件 ;-- 將 作者 `辰東`的書籍 全部漲價 50% update t_book set price = price * 1.5 , update_time = now() where author = '辰東' ;

where 條件

適用于 修改、刪除、和查詢

  • 關系條件 > , >= , < , <= = 和 != 或者 <>(不等號)
-- 將 價格 低于50的 書籍 全部 下架 update t_book set status = '0', update_time = now() where price < 50 ;
  • 邏輯條件 and (與) or(或)
-- 將 價格 在 30 以下 或者 作者 為 辰東 的書籍 全部 上架 update t_book status = '1' , update_time = now() where price < 40 or author = '辰東' ;
  • 枚舉條件 in , not in
-- 修改 書籍編號 1, 3 , 5 的書籍信息,將價格 + 10 元 update t_book set price = price + 10 where id in (1, 3, 5) ;
  • 區間條件 between … and
-- 查看書籍價格在 30 ~ 50 之間的書籍信息 select * from t_book where price >=30 and price <=50 ; select * from t_book where price between 30 and 50 ; -- 前后都包含
  • 空值查詢 is null / is not null
-- 將 書籍作者為空的 書籍 作者 設置為 匿名 update t_book set author = '匿名' where author is null ;
  • 模糊查詢條件 like

    %(百分號)_ (下劃線)
    匹配 任意 0~ N個字符匹配 任意 1個字符
-- 查詢 圖書名 以 神 開頭的 書籍 select * from t_book where book_name like '神%' ; -- 查詢 作者 以 ... 東結尾的 書籍 select * from t_book where author like '%東' ; -- 查看 作者 中 包含 小東 的 書籍 select * from t_book where author like '%小東%' ;-- 查看 圖書名以 神開頭 、且 長度 為2 的數據 select * from t_book where book_name like '神_' ;

刪除數據 DELETE

  • 全表刪除
delete from <tableName> ; -- 刪除表中所有數據 (慎用)-- 假如 確定要刪除表中所有的數據,那么也不推薦使用 delete , 因為 delete 只刪除數據、而不刪除 數據所占用的空間truncate table <tableName> ; -- 刪除表中所有數據的 推薦寫法, 原因是 不僅僅把數據刪了,還把數據占用的空間也清除了
  • 帶條件刪除
delete from <tableName> where 條件 ; -- 條件 請參數 where 條件的用法

查詢數據

  • 簡單查詢
  • 子查詢
  • 嵌套查詢
  • 集合查詢
  • 關聯查詢

簡單查詢

  • SELECT 查詢
  • 基于表的查詢
  • where條件查詢
  • group by分組查詢
  • having 分組篩選查詢
  • order by排序
  • limit 分頁查詢

SELECT 查詢

select 1 ; -- 一般是系統進行心跳檢測使用的 select now() ; -- 獲取當前系統時間 select version() ; -- 獲取數據庫版本號 select user() ; -- 獲取 當前登錄的用戶信息

基于表的查詢

select <columnName>, <columnName> , ... from <tableName> ;

如果要查詢 表中所有的列,可以是用 *來代替

不推薦使用 select * 來查詢數據、因為這種查詢 性能低

再查詢列的時候,還可以給列 設置別名 select as , as 還可以省略不寫

tableName 也可以 設置 別名

where條件查詢

請參考 where條件

group by 分組查詢

  • 聚合函數 :將多條記錄進行一個聚合,返回一條記錄, 聚合函數不會對空值參與統計
count : 統計個數-- 查詢 書籍表中 有多少 書籍 select count(id) from t_book ; select count('*') from t_book ; select count(1) from t_book ; PS : 性能: count(id) > count(1) > count('*') , 如果統計字段,那么 空值不參與統計的sum : 求和-- 查看所有圖書的總價, sum 只能統計 字段 select sum(price) from t_book ; avg : 求平均值 max : 求最大值 min : 求最小值
  • 分組 一般都需要配合 聚合函數實現數據的查詢
-- 查詢 書籍表 每個作者有多少本書 select count(1), author from t_book where author is not null group by author ;

分組查詢 對查詢的字段 是有要求的

  • 查詢的字段出現在 聚合函數中
  • 查詢的字段出現在 group by 的后面
  • having 分組篩選

    -- 查詢 書籍表 中 價格 相同的 價格 select price from t_book group by price having count(1) > 1-- 查詢 書籍表中, 同作者的 書籍平均價格 > 40 的作者信息 select author from t_book group by author having avg(price) >40;
    where 和 having的區別

    where 是對表中的每一條記錄 進行篩選和過濾, having 是對 分組后的結果 進行篩選和過濾

    where 比 having 先執行, 能用 where 進行過濾 就不要使用 having 過濾

    order by 排序

    ascdesc
    升序,如果不指定排序規則, 默認升序降序
    -- 根據圖書價格 降序排列 select * from t_book order by price desc ; -- 多字段排序 select * from t_book order by price desc , create_time desc ;

    當有多個字段進行排序的時候,只有當前面的字段 值相同的時候,才會使用 后面指定的字段進行排序。

    limit 分頁查詢

    select * from t_book order by price desc limit [<offset>, ] <rows>

    offset : 查詢數據的偏移量,默認從0開始,可以省略,如果省略, 代表 值為 0

    rows : 每頁查詢的條數

    offset = (page - 1) * rows , page 代表頁碼

    簡單查詢的完整SQL結構

    select <coloumnName> .... from <tableName> where <condition> group by column, ... having <condition> order by column <desc|asc> limit offset , rows ;

    子查詢

    • 基于列的子查詢
    • 基于條件的子查詢

    基于列的子查詢

    子查詢 出現在 查詢的列上

    -- 查詢 用戶為1 的 手機號,郵箱和真實姓名 select tel ,email, (select real_name from t_user_info where user_id = u.id ) as real_name from t_user u where id = 1;

    所有的子查詢都必須用 括號 括起來

    基于列的子查詢 , 子查詢 必須返回的是 單列 單值

    基于條件的子查詢

    子查詢出現在 where 條件上

    • 關系條件子查詢
    -- 查詢 書籍表中 價格最高的 圖書信息 select * from t_book where price = (select max(price) from t_book); -- 查詢 書籍表中 價格超過 所有書籍價格平均值的 圖書信息 select * from t_book where price > (select avg(price) from t_book) ; -- 查詢 書籍表中 同一個作者所有書籍 超過他自己書籍的平均值的 圖書信息 select * from t_book b where b.price >(select avg(price) from t_book t where t.author = b.author)

    關系條件子查詢 返回的是 單列 單值

    • in 子查詢
    -- 查詢 一本書 以上的所有作者 select * from t_book where author in (select author from t_book group by author having count(1) > 1 );

    基于 in 條件子查詢,返回的是 單列 多值

    • exists 子查詢
    -- 查詢 一本書 以上的所有作者 select * from t_book b where exists ( select 1 from (select author from t_book group by author having count(1) > 1 ) a where b.author = a.author )-- 查詢 書籍表中 同一個作者所有書籍 超過他自己書籍的平均值的 圖書信息 select * from t_book b where exists (select 1 from (select avg(price) avg, author from t_book group by author) awhere a.author = b.author and b.price > a.avg );

    子查詢 和 主查詢 在數據上有一定的關聯關系

    嵌套查詢

    • 將一個查詢的結果、當作一張表、繼續對這個查詢的結果表 進行查詢的過程
    select a.* from (select author, count(1) count from t_book group by author ) a ;

    在嵌套查詢中,查詢出來的 臨時表 在使用的時候,必須設置 別名

    with 臨時表查詢

    with temp as (select author, count(1) count from t_book group by author ), temp2 as (select * from t_user where ..... ; ) select * from temp , temp2 ;

    MySQL 8.0 支持的寫法

    集合查詢

    • 并集 union 或者 union all
    -- 查詢 金庸 對應的 書籍個數 和 最高價格 select author, count(1) count , max(price) max from t_book where author = '金庸' union -- 查詢 古龍 對應的 書籍個數 和最高價格 select author, count(1), max(price) from t_book where author = '古龍' ;

    集合查詢 最終查詢的結果 字段名 以 第一個 SQL語句 為準

    集合查詢中 連接的多個 查詢語句,查詢的列的個數 和 列的含義 必須保持一一對應

    union 會將多個查詢的結果 合并到一塊,自動去除重復的數據

    Union all 會將多個查詢的結果 合并到一塊,不會 去重

    • 交集 intersect
    • 差集 minus

    關聯查詢

    • 表與表之間如果有關聯關系、或者數據與數據之間有關聯關系,那么可以采用關聯查詢進行數據的查詢

    關聯關系

    • 一對一
    • 一對多/多對一
    • 多對多

    關系型數據庫 是非常善于處理關聯關系的,那么 關聯關系 主要是通過 外鍵 實現的

    一對一(one to one)的關聯關系

    一對一的關聯關系 在 生活中,是比較少見的。例如 用戶 和 用戶信息 的關系

    一對一的關聯關系 讓 兩個表 形成 主表 和 附表 的關系,通常在 附表 中 維護 主表的關系

    一對一的關系維護方式 通常由2種,

    ? 第一種是 外鍵 + 唯一鍵 實現

    ? 第二種是 主鍵共享 實現的

    外鍵 + 唯一鍵 實現 一對一的關聯關系 create table t_user(id int primary key auto_increment , tel varchar(11) unique not null comment '手機號', password varchar(128) not null comment '密碼' ,email varchar(50) not null comment '郵箱' ,create_time datetime comment '注冊時間', last_login_time datetime comment '最近登錄時間', status tinyint default 1 comment '賬戶狀態, 0 拉黑 -1 刪除' );create table t_user_info (id int primary key auto_increment , real_name varchar(50) comment '真實姓名', nick_name varchar(50) comment '昵稱', -- 維護關系的 外鍵user_id int unique comment '用戶ID', -- 通常需要給 外鍵 添加約束constraint t_user_info_user_fk_user_id foreign key(user_id) references t_user(id) ); 主鍵共享 實現 一對一的關聯關系create table t_user(id int primary key auto_increment , tel varchar(11) unique not null comment '手機號', password varchar(128) not null comment '密碼' ,email varchar(50) not null comment '郵箱' ,create_time datetime comment '注冊時間', last_login_time datetime comment '最近登錄時間', status tinyint default 1 comment '賬戶狀態, 0 拉黑 -1 刪除' );create table t_user_info (id int primary key , -- 不能使用自動增長real_name varchar(50) comment '真實姓名', nick_name varchar(50) comment '昵稱', constraint t_user_info_fk_id foreign key (id) references t_user(id) ) ;
    一對多(one to many)的關聯關系
    • 資源表 —> 資源 和 用戶 是 多對一的 ,一個用戶可以上傳多個資源,而一個資源 一定屬于 某一個用戶上傳的
    create table t_resource(id int primary key auto_increment , resource_name varchar(100) not null comment '資源名稱', resource_desc text comment '資源描述',keywords varchar(200) comment '關鍵字',score int comment '資源積分', size bigint comment '資源大小' ,ext varchar(20) comment '資源后綴', resource varchar(100) not null comment '資源', type_id int comment '資源類型ID', -- 關系屬性 ???user_id int comment '上傳的用戶ID',foreign key(user_id) references t_user(id),foreign key(type_id) references t_resource_type(id) );

    在 一對多 的關系中, 在 多的一方,維護一 的 一方 的關系

    多對多 (many to many)的 關聯關系
    • 用戶 和 角色的關系 是 多對多的, 一個用戶 可以安排多個角色, 一個角色下可以由多個用戶
    create table t_role (id int primary key auto_increment , role_name varchar(50) comment '角色名', role_desc varchar(200) comment '角色描述' );-- 第一種 中間表的 創建方式 (常用的方式) create table t_role_user (id int primary key auto_increment , role_id int , user_id int ,foreign key (role_id) references t_role(id) ,foregin key(user_id) references t_user(id) );-- 第二種 中間表的 創建方式 (采用 聯合主鍵的方式) create table t_role_user (role_id int ,user_id int ,foreign key (role_id) references t_role(id) ,foreign key(user_id) references t_user(id) ,-- 聯合主鍵primary key(role_id, user_id) );

    在 多對多的關系中, 通常使用 中間表 來維護關系

    數據與數據間的關系
    create table t_resource_type(id int primary key auto_increment , type_name varchar(50) comment '資源類型名' ,pid int comment '上一級資源ID' , foreign key(pid) references t_resource_type(id) ) ;

    關聯查詢

    • 左外連接 left [outer] join … on
    • 右外連接 right [outer] join … on
    • 內連接 [inner] join … on
    -- 查詢 管理員 上傳的所有資源 select t.*, e.role_name, e.role_desc from t_resource t inner join t_role_user r on t.user_id = r.user_id inner join t_role e on e.id = r.role_id where e.role_name = '管理員'

    左連接: 以左表為主表,將相關的數據查詢出來,如果右表沒有相關連的數據,則以 空表示

    右連接:以右表為主表,將相關的數據查詢出來,如果左表沒有相關聯數據,則以空表示

    內連接:只查詢兩表 具有關聯關系的數據

    函數

    • 字符串函數
    函數名示例說明
    char_lengthchar_length(‘完美世界’) // 4獲取字符串長度
    concatconcat(‘a’ , ‘b’, ‘c’) // abc拼接多個字符串,如果有為 null 的值,結果為 null
    concat_wsconcat(’-’ , ‘a’, ‘b’, ‘c’) // a-b-c以某一個特定分隔符,拼接多個字符串
    insertinsert(‘guest’ , 2, 1, ‘wh’) // gwhestinsert(str, pos , len , newstr) 從 pos位置替換 len長度,內容為 newstr
    lower/lcaselower(‘ABC’) // abc轉小寫
    upper / ucaseupper(‘abc’) // ABC轉大寫
    substr/substringsubstr(‘abcd’, 2, 3) // ubs從 指定位置,截取多長,如果沒有設置長度,代表截取到尾部
    trim/ltrim/rtrimtrim(’ abc ') // abc去除前后空格
    reversereverse(‘abc’) // cba反轉字符串
    • 數學函數
    函數名示例說明
    abs求絕對值
    ceil向上取整
    floor向下取整
    round(x, y)四舍五入,保留y 位小數
    • 日期函數
    函數名示例說明
    now()獲取當前系統時間
    month(date)獲取月份
    year(date)獲取年份
    dayofmonth(date)獲取天
    DATE_ADDDATE_ADD(now() , interval 1 year)添加1年
    DATE_SUBDATE_SUB(now() , interval 1 hour)減少1小時
    DATEDIFFDATEDIFF(now(), date)計算兩個日期間隔的天數
    DATE_FORMATDATE_FORMAT(date, ‘%Y-%m-%d %H:%i:%s’)日期格式化
    • 條件函數
    函數名示例說明
    ifif(expr , v1, v2)expr 如果返回true, 取 v1, 否則 取 v2
    ifnullifnull(expr , v1)expr如果返回 null, 取 v1, 否則 取 expr
    case … when相當與 多分支條件判斷
    • 加密函數
    函數名示例說明
    md5md5(str)對字符串進行 MD5加密

    視圖View

    • 是一個虛擬的表,本質上是一個 SQL查詢語句,是真實表的一個數據映射
    • 作用: 1. 簡化查詢, 2. 提高數據的安全性( 和 授權有關 )

    視圖的創建

    create [or replace] view <viewName> as select .... ;

    視圖 一般不推薦 刪除數據、修改數據、新增數據

    視圖是一個真是表的數據映射,操作數據本質上還是操作 真實的表,

    視圖的結果有可能來自 聚合查詢,所以無法進行刪除和修改等操作

    刪除視圖

    drop view [if exists] <viewName>

    索引 Index

    如果表中的數據過大、那么查詢的速度就會逐漸變慢,所以需要對查詢做優化,

    那么索引 是 提高查詢效率的 有效手段之一

    索引 是 基于字段的、一張表中索引不是越多越好,因為索引過多,會導致索引維護困難

    索引的種類

    • 唯一索引 unique
    • 普通索引 normal
    • 倒排索引 fulltext (全文檢索)

    什么樣的字段適合添加索引

    • 主鍵 自帶索引
    • 唯一鍵自帶 唯一索引
    • 外鍵 自帶索引
    • 字段 的值 在整個表中 重復概率 很低、適合添加索引
    • 經常會出現在 where 條件上的字段 適合添加索引

    創建索引

    create [unique|fulltext] index <indexName> on <tableName>(columName, ...) ;

    刪除索引

    drop index 索引名 on <tableName> ; alter table <tableName> drop index 索引名 ;

    分析 SQL 語句

    explain select ....

    索引失效

    • 模糊查詢 — 前模糊 會導致 索引失效
    • 條件字段上使用 函數 ,會導致索引失效
    • != 查詢 也會導致索引失效

    總結

    以上是生活随笔為你收集整理的3.表数据的CRUD的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。