如何为插入SQL添加动态计数器

时间:2019-07-12 02:08:12

标签: php postgresql

我想添加一个计数器以显示每个查询插入的记录顺序。

if(isset($_POST['keyword'])){
    $keyword = $_POST['keyword'];
    if($keyword){   
        foreach($keyword as $row){          
            $keyword_exe = $con->prepare("
                INSERT INTO t_theme(m_id,keyword,sequence_counter)VALUES('$id','$row', '???')
            ");
            $keyword_exe->execute();            
        }
    }
    }

我希望输出如下:

postgresql_table

2 个答案:

答案 0 :(得分:0)

$counter = 0;
$pre_row = 0;
foreach($keyword as $row){   
   if( $pre_row  == $id){
       //In row m_id value equal to next value increase counter by 1
       $counter++;
   }else{
       //else start to 1
       $counter = 1;
       $pre_row = $id;
   }

    $keyword_exe = $con->prepare("
        INSERT INTO t_theme(m_id,keyword,sequence_counter)VALUES('$id','$row', '$counter')
    ");
    $keyword_exe->execute();            
}

DEMO

答案 1 :(得分:0)

我没有使用INSERT进行测试,但是在选择时可以使用它

ROW_NUMBER() OVER(PARTITION BY m_id ORDER BY id ASC) sequence_counter

为了节省一些数据库空间

More here