mysql 根據查詢條件進行update


-- 新增comment_num 評論數字段
alter table tb_tips add   `comment_num` int(11) NOT NULL DEFAULT '0' COMMENT '評論數';

select count(1) as comment_num ,tips_id from tb_tips_comments GROUP BY tips_id ;

-- 創建臨時表存儲 所有tips 的統計數量
create temporary table statistical_comments(select count(1) as comment_num ,tips_id from tb_tips_comments GROUP BY tips_id);


-- 把評論表中有的數據但是tips表沒有的數據清理掉
select tb_tips.tips_id ,statistical_comments.tips_id  from tb_tips right join statistical_comments on tb_tips.tips_id = statistical_comments.tips_id where  tb_tips.tips_id is null ;

delete FROM  tb_tips_comments where tips_id in (select statistical_comments.tips_id  from tb_tips right join statistical_comments on tb_tips.tips_id = statistical_comments.tips_id where  tb_tips.tips_id is null);
-- 把統計的評論數同步到tips表格
update tb_tips,statistical_comments set tb_tips.comment_num = statistical_comments.comment_num where tb_tips.tips_id = statistical_comments.tips_id;

-- 查看結果是否和預期一樣。
select count(1) as comment_num ,tips_id from tb_tips_comments GROUP BY tips_id ORDER BY comment_num ,tips_id;
select comment_num,tips_id from tb_tips where comment_num >0 ORDER BY comment_num ,tips_id ;
    -- 用完釋放
drop TEMPORARY TABLE statistical_comments;

 

 


免責聲明!

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



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