() ( MySQL 5.7 MariaDB).
CREATE TABLE bills (
id_interess INT UNSIGNED NOT NULL,
bill_dt DATETIME DEFAULT CURRENT_TIMESTAMP,
bill_year YEAR AS (year(bill_dt)),
year_position INT UNSIGNED NULL,
id_bill VARCHAR(30) AS (concat(date_format(bill_dt, '%Y%m%d-'), year_position)),
PRIMARY KEY (id_interess),
INDEX (bill_year, year_position)
) ENGINE=InnoDB;
bill_year
id_bill
. . - bill_year
, , ( ).
:
insert into bills(id_interess, year_position)
select 1, coalesce(max(year_position), 0) + 1
from bills
where bill_year = year(now());
:
insert into bills(id_interess, bill_dt, year_position)
select 10, '2016-01-01', coalesce(max(year_position), 0) + 1
from bills
where bill_year = year('2016-01-01')
: https://www.db-fiddle.com/f/8pFKQb93LqNPNaD5UhzVwu/0
, , year_postion
:
CREATE TRIGGER bills_after_insert BEFORE INSERT ON bills FOR EACH ROW
SET new.year_position = (
SELECT coalesce(max(year_position), 0) + 1
FROM bills
WHERE bill_year = year(coalesce(new.bill_dt, now()))
);
insert :
insert into bills(id_interess) values (1);
insert into bills(id_interess, bill_dt) values (11, '2016-02-02');
select:
select id_interess, id_bill
from bills
order by id_bill;
: https://www.db-fiddle.com/f/55yqMh4E1tVxbpt9HXnBaS/0
Update
, insert:
insert into bills(id_interess, id_bill)
select
@id_interess,
concat(
date_format(@date, '%Y%m%d-'),
coalesce(max(substr(id_bill, 10) + 1), 1)
)
from bills
where id_bill like concat(year(@date), '%');
@id_interess
@date
. @date
CURDATE()
, , . . 2016 , 2017 .
: http://rextester.com/BXK47791
LIKE
WHERE
id_bill
( ), . . , MAX. insert, .