select判斷+insert插入的原子操作 pgsql


使用insert into tablA select * from tableB語句時,

一定要確保tableB后面的where,order或者其他條件,都需要有對應的索引,

來避免出現tableB全部記錄被鎖定的情況。

 

通過sql一步處理

insert into table_name(column1,column2,column3) 
select 'value1','value2','value3'
where (select column from table_name where id=1) is null;

 

eg:

insert into subscribe_member(openid,msg_title,can_times)
select 'hhhh','biaoti',1
where (select openid from subscribe_member where id=1) is null;

 

 

使用insert into tablA select * from tableB語句時,一定要確保tableB后面的where,order或者其他條件,都需要有對應的索引,來避免出現tableB全部記錄被鎖定的情況。

 

https://mp.weixin.qq.com/s/B5WkFW0RkR7HgbyUdd7BFw

 

最終的sql:

 

INSERT INTO order_record SELECT
    * 
FROM
    order_today FORCE INDEX (idx_pay_suc_time)
WHERE
    pay_success_time <= '2020-03-08 00:00:00';

 

 

補充:

force index() 指令可以指定本次查詢使用哪個索引!一條sql只會用到一個索引,mysql優化器會計算出一個合適的索引,但是這個索引不一定是最好的。force index()指令可以避免MySql優化器用到了一個低效的索引。

mysql可能並不總會選擇合適且效率高的索引去查詢,這時適當的force index(indexname) 強制告訴mysql使用什么索引尤為重要。

 


免責聲明!

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



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