PostgreSQL 实现MySQL "insert ignore" 语法。

对MySQL熟悉的人可能都知道,MySQL 有一个“insert ignore" 语法来忽略已经存在的记录。 PostgreSQL暂时不提供这样的语法,但是可以用其他方法来代替。


以下为本次演示的样例表结构以及数据。
t_girl=# \d insert_ignore                         
           Table "ytt.insert_ignore"
  Column  |          Type          | Modifiers 
----------+------------------------+-----------
 id       | integer                | not null
 log_time | time without time zone | 
Indexes:
    "insert_ignore_pkey" PRIMARY KEY, btree (id)


t_girl=# select * from insert_ignore;
 id |    log_time    
----+----------------
  1 | 14:44:12.37185
(1 row)




我来演示下几种代替方法。


第一种方法, 用自带的规则(RULE)来实现。


t_girl=# create rule r_insert_ignore as on insert to insert_ignore where exists (select 1 from insert_ignore where id = new.id) do instead nothing;    
CREATE RULE


这时,我们插入两条记录,其中一条的主键值已经存在,直接忽略掉。 实际插入的记录数为1.
t_girl=# insert into insert_ignore values(1,current_time),(2,current_time);
INSERT 0 1
t_girl=# select * from insert_ignore;
 id |    log_time     
----+-----------------
  1 | 14:44:12.37185
  2 | 14:48:22.222848
(2 rows)



第二种方法, 建立一个返回NULL的触发器函数。 那么函数体如下:


t_girl=# create or replace function sp_insert_ignore() returns trigger as 
 $ytt$
 begin
   perform  1 from insert_ignore where id = new.id;
   if found then
     return null;
  end if;
  return new;
end;
$ytt$ language 'plpgsql';
CREATE FUNCTION


对应的触发器如下:
t_girl=# create trigger tr_ib_insert_ignore before insert on insert_ignore for each row execute procedure sp_insert_ignore();
CREATE TRIGGER


继续插入两条记录。
t_girl=# insert into insert_ignore values (3,current_time),(2,current_time);
INSERT 0 1
t_girl=# select * from insert_ignore;
 id |    log_time     
----+-----------------
  1 | 14:44:12.37185
  2 | 14:48:22.222848
  3 | 15:05:33.198847
(3 rows)


OK。目的达到了。



第三种方法,用WITH来实现。


t_girl=# insert into insert_ignore 
		with ytt_test(f1,f2) as (
							values(6,current_time),(3,current_time)
							) 
							select a.* from ytt_test as a where a.f1 not in (select id from insert_ignore as b);                          
INSERT 0 1
查看记录,插入了一条ID为6的记录,忽略了ID为3的记录。
t_girl=# select * from insert_ignore;
 id |    log_time     
----+-----------------
  1 | 14:44:12.37185
  2 | 14:48:22.222848
  3 | 15:05:33.198847
  6 | 15:15:52.297802
(4 rows)




第四种,用存储过程来代替INSERT处理。

t_girl=# create or replace function sp_insert_ignore (
IN f_id int,
IN f_log_time time without time zone
) returns void as 
$ytt$
begin
  insert into insert_ignore values (f_id,f_log_time);
  exception   when unique_violation  then
    raise notice 'Duplicated Key Error on ID:%',f_id;
    return;
end;
$ytt$ language plpgsql;


第一次调用,抛出了错误。
t_girl=# select sp_insert_ignore(1,'14:22:35'::time); 
NOTICE:  Duplicated Key Error on ID:1
 sp_insert_ignore 
------------------
 
(1 row)


第二次正常插入。
t_girl=# select sp_insert_ignore(8,'14:22:35'::time);
 sp_insert_ignore 
------------------
 
(1 row)


t_girl=# select * from insert_ignore;
 id |    log_time     
----+-----------------
  1 | 14:44:12.37185
  2 | 14:48:22.222848
  3 | 15:05:33.198847
  6 | 15:15:52.297802
  8 | 14:22:35
(5 rows)


t_girl=# 

OK,目的也达到了。





### MySQL 插入语句报错解决方案 #### 一、除数为零错误 在执行 `INSERT INTO SELECT FROM` 操作时,如果查询的结果集中存在除法运算且分母可能出现为零的情况,则会触发 “division by 0”的错误。为了避免这种情况,在构建视图或编写 SQL 查询逻辑时应该提前考虑并处理潜在的被零除的风险。 可以采用 `CASE WHEN` 结构来规避此风险: ```sql SELECT column_name, CASE WHEN divisor_column = 0 THEN NULL -- 当除数等于0时返回NULL或其他默认值 ELSE dividend_column / divisor_column END AS result_column FROM source_table; ``` 这样可以在源头处防止非法操作的发生[^1]。 #### 二、主键冲突问题 对于因重复主键而导致无法正常插入新纪录的情形,有几种常见方法可用来解决问题: - **使用UUID作为唯一标识符**: 对于每一条新增加的数据项都生成一个新的全局唯一的字符串形式ID(即去除连字符后的uuid),从而确保不会发生主键碰撞。 ```sql INSERT INTO target_table(id, col_a, col_b,...) VALUES(REPLACE(UUID(), '-', ''), val_a, val_b,...); ``` - **忽略已存在的记录** : 如果允许部分失败而继续完成其余成功的写入动作的话,那么可以通过设置特定参数让MySQL跳过那些违反约束条件的部分行. ```sql INSERT IGNORE INTO target_table(col_x,col_y,...) SELECT s.col_x,s.col_y,... FROM some_other_table AS s ; ``` - **更新已有条目而非抛出异常** :利用ON DUPLICATE KEY UPDATE子句实现当检测到主键重复时不终止整个事务而是修改对应字段的内容. ```sql INSERT INTO target_table(key_col,val_col) VALUES('key_value','new_val') ON DUPLICATE KEY UPDATE val_col='updated_new_val'; ``` 以上三种方式可以根据实际业务需求灵活选用以应对不同的场景下的主键冲突情况[^5]. #### 三、锁机制引发的问题 有时即使语法正确也可能因为并发控制策略不当造成死锁或者其他类型的锁定等待超时现象进而阻止了正常的DML(DATABASE MANIPULATION LANGUAGE)指令提交。针对这类状况建议优化表结构设计减少不必要的索引数量以及调整隔离级别等措施提高系统的吞吐性能;另外还可以尝试将大批次的操作拆分成更小规模的任务序列逐步推进直至全部结束[^4]. #### 四、跨库迁移兼容性差异 值得注意的是不同关系型数据库管理系统之间存在着细微的功能特性区别特别是在涉及到批量化加载外部源文件或者远程连接访问第三方服务接口方面尤为明显。比如PostgreSQL就要求其内部函数调用格式遵循严格的命名约定并且支持自定义类型转换规则这与其他主流产品略有差别因此务必仔细阅读官方文档确认目标平台的具体行为模式再着手实施具体的编程工作[^3].
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值