1. 程式人生 > 實用技巧 >mysql8學習筆記⑥資料庫常用操作之Delete/update語句

mysql8學習筆記⑥資料庫常用操作之Delete/update語句

mysql8學習筆記⑥資料庫常用操作之Delete/update語句

-- 找出課程表中沒有章節資訊的課程

select a.course_id,a.title

from imc_course a

left join imc_chapter b on b.course_id = a.course_id

where b.course_id IS NULL

-- 刪除課程表中沒有章節資訊的課程

delete a

from imc_course a

left join imc_chapter b on b.course_id = a.course_id

where b.course_id IS NULL

-- 刪除課程方向表中重複的課程方向,

-- 保留方向ID最小的一條,並在方向名稱上新增唯一索引(如果課程方向重複則不能新增唯一索引)

-- 找出重複的課程型別
select type_name,count(*)
from imc_type
group by type_name having count(*) > 1

-- 最小的type_id
select type_name,min(type_id) as min_type_id,count(*)
from imc_type
group by type_name having count(*) > 1


delete a
from imc_type a
join ( select type_name,min(type_id) as min_type_id,count(*) from imc_type group by type_name having count(*) > 1 ) b on a.type_name=b.type_name and a.type_id > b.min_type_id create unique index uqx_typename on imc_type(type_name);

Update使用order by和limit語句可以限制更新的資料量,當我們對某個資料表很大的業務進行更新時,比如更新100W資料,如果一次全部更新會引發主從延時、大面積阻塞,用limit 限制可以迴圈分批進行更新

更新示例:

-- 凍結使用者“沙佔”的賬號

select user_nick,user_status

from imc_user

where user_nick = '沙佔'

update imc_user

set user_status=0

where user_nick = '沙佔'

-- 隨機推薦10門課程

alter table imc_course
add is_recommand tinyint default 0 comment '是否推薦,0不推薦,1推薦';

select course_id
from imc_course
order by rand()
limit 10;


update imc_course
set is_recommand=1
order by rand()
limit 10;

select course_id,title
from imc_course
where is_recommand=1;

-- 利用課程表中的平均評分,更新課程表中課程的評分

select * from imc_classvalue;

update imc_course a 
join(
        select course_id,
                avg(content_score) as avg_content_score,
                avg(level_score) as avg_level_score,
                avg(logic_score) as avg_logic_score,
                avg(score) as avg_score
        from imc_classvalue
        group by course_id
) b on a.course_id = b.course_id
set a.content_score = b.avg_content_score,
a.level_score = b.avg_level_score,
a.logic_score = b.avg_logic_score,
a.score = b.avg_score
;

-- 每門課程的學習人數佔總課程總學習人數的百分比

with tmp as(

select class_name,title,study_cnt

,sum(study_cnt) over(partition by class_name) as class_total

from imc_course a

join imc_class b on b.class_id = a.class_id

)

select class_name,title,concat(study_cnt/class_total*100,'%')

from tmp

order by class_name;