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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题