我有一张表:
id col1 col2 receipt_id receipt_year
1 ddd ggg 1 2018
2 ddd eee 2 2018
我需要为每个新年重置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;
}
这是否正确?
答案 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;