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

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 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题