php和postgres每年重置收据ID

时间:2018-03-20 10:32:33

标签: php postgresql

我有一张表:

id  col1  col2  receipt_id  receipt_year
1   ddd   ggg   1           2018
2   ddd   eee   2           2018
  • id 列是 bigserial receipt_id bigint
  • receipt_id receipt_year 是唯一键
  • id 是主键

我需要为每个新年重置receipt_id,例如:

id  col1  col2  receipt_id  receipt_year
1   ddd   ggg   1           2018
2   ddd   eee   2           2018
3   lol   lpl   1           2019

目前我这样做:

$current_year = date('Y');
$sql = SELECT MAX(receipt_id) AS receipt_id FROM table WHERE receipt_year=:year;
$stmt = $conn->prepare($sql);
$stmt->execute(array(':year' => $current_year));
$receipt_ido = $stmt->fetchColumn();

if ( ! empty($receipt_ido)) {
   $receipt_id = ($receipt_ido + 1);
} else {
   $receipt_id = 1;
}

这是否正确?

1 个答案:

答案 0 :(得分:0)

如果你想生成 receipt_id,使用ROW_NUMBER就可以轻松完成了:

SELECT
    id, col1, col2,
    ROW_NUMBER() OVER (PARTITION BY receipt_year ORDER BY id) receipt_id,
    receipt_year
FROM yourTable;