我有一张名为Flights
的表格。该表具有以下结构:
+----+----------+---------------+
| Id | Name | DepartureDate |
+----+----------+---------------+
| 1 | 20130001 | 2013-02-14 |
| 2 | 20130002 | 2013-05-04 |
| 3 | 20140001 | 2014-01-16 |
| 4 | 20130003 | 2013-07-15 |
| 5 | 20150001 | 2015-01-01 |
| 6 | 20150002 | 2015-09-14 |
+----+----------+---------------+
如您所见,航班的名称取决于出发日期的年份和相关数字。
问题在于,当我想插入一个航班时,即2013年,我必须进行SELECT COUNT(*)
查询以获取该表中该年度的航班数量,然后制作{{1}声明。我认为这很糟糕且效率低下,因为它可能是重复的航班号。
您建议做什么操作?
答案 0 :(得分:1)
如果您正在使用(或可以切换到)MyISAM Engine,您应该使用MySQL的AUTO_INCREMENT
。
要观看此工作:http://sqlfiddle.com/#!9/c6af9/1
CREATE TABLE flights (
year ENUM('2013','2014','2015') NOT NULL,
id MEDIUMINT NOT NULL AUTO_INCREMENT,
DepartureDate date NOT NULL,
PRIMARY KEY (year,id)
) ENGINE=MyISAM;
然后在你之前插入或像这样插入:
INSERT INTO flights (year, DepartureDate) VALUES ('2013', date('2013-07-03')),
('2014', date('2014-06-03')), ('2013', date('2013-02-06')),
('2015', date('2015-01-04')), ('2015', date('2015-02-04')),
('2015', date('2015-12-10')), ('2015', date('2015-06-04')),
('2015', date('2015-11-04')), ('2015', date('2015-10-04')),
('2015', date('2015-01-07')), ('2015', date('2015-01-09')),
('2015', date('2015-01-09')), ('2015', date('2015-09-12')),
('2015', date('2015-02-09')), ('2015', date('2015-07-04'));
在寻找记录时,请执行以下操作:
SELECT CONCAT(year, LPAD(id, 4, '0')) AS name, DepartureDate FROM flights;
供进一步参考: http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html
答案 1 :(得分:0)
我仍然不确定你的目标是什么。
但只是我的猜测:
http://sqlfiddle.com/#!9/8dc5b/1
INSERT INTO flights
SELECT 7, MAX(Name)+1, @d
FROM flights
WHERE YEAR(DepartureDate)=YEAR(@d);
或
INSERT INTO flights
SELECT 7, MAX(Name)+1, date('2013-05-04')
FROM flights
WHERE YEAR(DepartureDate)=YEAR(date('2013-05-04'));
或者您的id
已经是AUTO_INCREMENT:
INSERT INTO flights
SELECT null, MAX(Name)+1, date('2013-05-04')
FROM flights
WHERE YEAR(DepartureDate)=YEAR(date('2013-05-04'));
答案 2 :(得分:0)
最后,我使用@Alex的建议使用了触发事件。
CREATE TRIGGER `flights_iu_trigger` BEFORE INSERT ON `flights`
FOR EACH ROW
BEGIN
DECLARE flight_name INT;
SELECT (IFNULL(MAX(Name), CONCAT(YEAR(NEW.DepartureDate),'0000')) + 1)
INTO flight_name FROM flights
WHERE YEAR(flights.DepartureDate) = YEAR(NEW.DepartureDate);
SET NEW.Name = flight_name;
END;
通过这些程序,我会根据出发年份自动设置新航班的名称