dounai1986 2017-07-31 08:34
浏览 337
已采纳

Postgresql查询检查id是否存在,如果不存在则会插入(临时)并且如果存在则回滚全部

I'm just a beginner with programming

I want to know if anyone have solution for my problem (PostgreSQL & Yii2)

I have one button to submit these array data (for this case just 5 rows):

+----+--------+
| id |  name  |
+----+--------+
| 1  | apple  |
| 2  | orange |
| 3  | manggo |
| 1  | fish   |
| 4  | meat   |
+----+--------+
  1. if id=1 not exist, insert record1 ( or to temp tbl )
  2. if id=2 not exist, insert record2 ( or to temp tbl )
  3. if id=3 not exist, insert record3 ( or to temp tbl )
  4. if id=1 not exist, insert record2 ( this one failed, cancel all 1,2,3 and stop )

Every step using 2 queries (SELECT COUNT & INSERT)

+----+--------+
| id |  name  |
+----+--------+
| 1  | apple  |
| 2  | orange |
| 3  | manggo |
| 4  | fish   |
| 5  | meat   |
+----+--------+

For second case after all proceed (until id=5 no record exist) commit to database

Thank you

  • 写回答

1条回答 默认 最新

  • douren4075 2017-07-31 13:45
    关注

    Make sure the id column has a unique constraint, assuming your id column is the primary key it should already have this. Open a transaction and then just insert the rows, if the id already exists the DB will throw an error. If an error is thrown catch it and perform a rollback, otherwise commit the transaction.

    Example:

    $data = [
        ['id' => 1, 'name' => 'Item 1'],
        ['id' => 2, 'name' => 'Item 2'],
        ['id' => 3, 'name' => 'Item 3'],
        ['id' => 4, 'name' => 'Item 4'],
        ['id' => 5, 'name' => 'Item 5'],
    ];
    
    $connection = Yii::$app->db;
    $transaction = $connection->beginTransaction();
    try {
        foreach ($data as $item) {
            $connection->createCommand()->insert('{{%your_table}}', $item)->execute();
        }
        $transaction->commit();
    } catch (\yii\db\IntegrityException $exception) {
        $transaction->rollBack();
    }
    

    I don't know how important it is for you to insert the id value yourself, but you might be better of using a serial for your id column.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题