【问题标题】:How can i get the unique key violating column name at the time of execution in postgresql如何在 postgresql 执行时获取违反列名的唯一键
【发布时间】:2020-09-05 02:42:11
【问题描述】:

我正在使用 foreach 循环插入多个表,并且我想要唯一键列名,因为它在运行时违反了唯一键约束,因此我可以修改值并插入它。

foreach ($data as $table_name){

 $sql="INSERT INTO $table_name ($column_name) VALUES ($column_vlues)"

$result=query_params($db_conn,$sql,$params)
 if($result){
  //Do nothing. Its fine
}else{
 //If its voileting the unique key contraints then change the column value like new column value = $column_name_which_voileting.$value and then insert it.
 }
}

如有任何帮助,将不胜感激。

【问题讨论】:

  • 它为您提供约束的名称,您可以从中推断出列名。您使用的是什么语言和 API?
  • PHP,Postgresql @LaurenzAlbe

标签: php sql postgresql


【解决方案1】:

您可以使用pg_get_result_error() 获取PGSQL_DIAG_MESSAGE_PRIMARY,其中将包含如下约束名称:

duplicate key value violates unique constraint "uni_id_key"

从中您可以提取约束的名称。然后您可以查询information_schema.constraint_column_usage 以查找与该约束关联的列(如果该约束跨越多个列,您可能不得不求助于pg_catalog.pg_constraint 来查找它们的相对位置)。

PostgreSQL 实际上会随错误消息一起发送纯约束名称,但 PHP 无法提取该错误响应字段。

【讨论】:

    猜你喜欢
    • 2011-05-25
    • 2016-10-24
    • 2018-04-15
    • 2022-08-12
    • 2016-09-28
    • 2018-03-24
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多