I have an auction application with these two tables (this is highly simplified, obviously):
create table auctions (
auction_id int,
end_time datetime
);
create table bids (
bid_id int,
auction_id int,
user_id int,
amount numeric,
bid_time timestamp,
constraint foreign key (auction_id) references auctions (auction_id)
);
I don’t want bids on an auction after that auction has ended. In other words, rows in the bids table should be allowed only when the bid_time is earlier than the end_time for that auction. What’s the simplest way to do this in MySQL?
Ufortunately MySQL does not have a
CHECKconstraint feature. But You should be able to enforce this using a trigger. However, MySQL trigger support isn’t as advanced or well optimized as it is in other RDBMS-es, and you will suffer a considerable performance hit if you do it this way. So if this is a real-time trading system with massive amounts of concurrent users, you should look for another solution.Note that the
SIGNALsyntax is available only since MySQL 5.5 (currently GA). Triggers are available since MySQL 5.0. So if you need to implement this in a MySQL version prior to 5.5, you need to hack your way around not being able to raise a signal. You can do that by causing some change in the data that will guarantee theINSERTto fail. For instance you could write:Since
acution_idis declaredNOT NULLin the table, the state of the data will be such that it cannot be inserted. The drawback is that you will get a NOT NULL constraint violation, and the application will have to guess whether this is due to this trigger firing or due to a “real” NOT NULL constraint violation.For more information, see: http://rpbouman.blogspot.nl/2009/12/validating-mysql-data-entry-with_15.html and http://rpbouman.blogspot.nl/2006/02/dont-you-need-proper-error-handling.html