set maximum limits in mysql sql database - mysql

I have 2 tables. Concerts / Tickets
I want to set Concert 1 to have maximum of 100 tickets and Concert 2 to have maximum of 200 tickets. so like have a concert_id be linked with a maximum number of ticket_id.
How can I do this in mysql? thanks

You can write triggers:
delimiter //
drop trigger if exists limitInsertsTrigger //
create trigger limitInsertsTrigger before insert on tickets
for each row
begin
declare msg varchar(128);
if (select count(*) from tickets where concert_id = new.concert_id)>
(select max_tickets_number from concert where id=new.concert_id)
then
set msg = concat('MyTriggerError: Trying to insert too many tickets');
signal sqlstate '45000' set message_text = msg;
end if;
end //
Remember to have a max_tickets_number column in the concert table.

Related

Can't create MySQL Trigger with several tables

I've got a database with 3 tables:
delivery
company
details
The company table has a column with ratings from 1 to 10 and if a rating is more than 5 we can understand that this company is reliable and in detail if the price is more than 1000 it is expensive detail.
Table delivery is connecting table for company and details Now I'm trying to create a trigger that will block Insert when somebody trying to add in table delivery expensive detail with an unreliable company, but I can't understand how to create Trigger using data from different tables.
I'm using MySQL
DELIMITER //
CREATE TRIGGER before_insert_1
BEFORE INSERT
ON delivery
FOR EACH ROW
IF company.rating < 5 AND detail.Det_Price > 1000 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Unreliable company';
END IF //
DELIMITER ;
You should review https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html paying particular attention to the discussion of NEW. values.
A simple version of the trigger might be like
DELIMITER //
CREATE TRIGGER before_insert_1
BEFORE INSERT
ON delivery
FOR EACH ROW
begin
declare vrating int;
declare vprice int;
select company.rating into vrating from company where company.id = new.company_id;
select detail.det_price into vprice from detail where detail.? = new.?;
IF vrating < 5 AND vPrice > 1000 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Unreliable company';
END IF ;
end //
DELIMITER ;
but since you didn't publish table definitions I can't tell you exactly how the selects should be.

How to fix Syntax Error in DATEDIFF trigger

Can anyone see what is wrong with this code?
Everything was working fine until I added the trigger to calculate the difference between two dates. First of all I altered the table just incase anyone wondered.
ALTER TABLE bookings
ADD COLUMN TheDuration varchar(10);
Then my triggers are as follows...
DELIMITER //
CREATE TRIGGER check_licence /*This trigger will approve customers with a valid licence */
BEFORE UPDATE ON customers
FOR EACH ROW
BEGIN
SET NEW.Status = CASE WHEN NEW.valid_licence = 'Yes'
THEN 'Approved'
ELSE 'Unapproved' /*So if a Customer has a valid licence, He will be automatically approved. */
/*But if he doesn't he will become unapproved[WORKING]*/
SET NEW.TheDuration = DATEDIFF(NEW.bookings.end_date, NEW.bookings.start_date) -- -- TO CALCULATE DURATION BETWEEN 2 DATES
END;
//
DELIMITER ;
The problem lays within
SET NEW.TheDuration = DATEDIFF(NEW.bookings.end_date, NEW.bookings.start_date) -- -- TO CALCULATE DURATION BETWEEN 2 DATES
As everything was working before I added this.
Same here...
DELIMITER //
CREATE TRIGGER Carperperson /* This Trigger Blocks a customer from renting two cars on the same name twice on one day. */
BEFORE INSERT ON bookings /*E.g. Mr.ABC cannot rent a Ford and a Nissan on the same day. Has to return first car first.[WORKING]*/
FOR EACH ROW
BEGIN
IF EXISTS (
SELECT 1
FROM bookings
WHERE NEW.customer_id = bookings.customer_id
AND ((new.start_date >= bookings.start_date
and new.start_date < bookings.end_date)
or (new.end_date > bookings.start_date
and new.end_date < bookings.end_date))
) THEN
SIGNAL SQLSTATE '45000'
set message_text='You can only book one car per single customer a day!' ; /* This triggers only allows to rent a car for 7 days, not more, not less[WORKING]*/
END IF;
IF ( NEW.end_date > NEW.start_date + INTERVAL 7 DAY ) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = '7 is the maximum. Please choose an earlier date.'; /*The end_date is more than seven days after start_date*/
END IF;
SET NEW.TheDuration = DATEDIFF(NEW.bookings.end_date, NEW.bookings.start_date) -- -- TO CALCULATE DURATION BETWEEN 2 DATES
END;
//
DELIMITER ;
Problem lays within...
SET NEW.TheDuration = DATEDIFF(NEW.bookings.end_date, NEW.bookings.start_date) -- -- TO CALCULATE DURATION BETWEEN 2 DATES

Set a limit occurrence for a value in a mysql table

So let's say i have a table that has a column "id_author" , i'd like to set a limit for the occurrence of the same value ; example : can't have more than 3 same "id_author" values so when i insert the 4th one it's refused.
Is there a way to implement this? Thanks
You can use a trigger before insert, that will throw a signal in case it violates your condition:
CREATE TRIGGER tooManyRecords
BEFORE INSERT ON yourTable
FOR EACH ROW
BEGIN
DECLARE counter INTEGER;
SELECT COUNT(*) INTO counter FROM yourTable
WHERE id_author = NEW.id_author;
IF counter >= 3 THEN
SIGNAL SQLSTATE '45000' SET message_text = 'there are already 3 records for the provided id';
END

How to create a before insert trigger based on previously inserted values in the table

I have a table which contains two columns
1.Clanid
2.Active
My problem is that i dont want any value in Clanid column to be inserted in this table if this value is already in Clanid column and Active for that value is 1.
For example
Clanid Active
1 1
2 1
3 0
Now it should not be possible to insert a record with Clanid=1 and Active=1 but i can insert Clanid=3 and Active=1 as this record is not there.
Try this:
delimiter //
create trigger unique_clanid
before insert on mytable
for each row
begin
if new.active and exists (
select * from mytable
where clanid = new.clanid
and active) then
signal sqlstate '02000' set MESSAGE_TEXT = 'Duplicate ClanID';
end if;
end//
delimiter ;
I think you should handle in your app level, but you want to handle in DB lavel, you can write trigger check it
you can check count record ( where Clanid = #param and Active =1)
if count > 1 : rollback
I am not available mysql to test , i just can describe my solution as following ( i;m not sure the syntax correct, it is too long time i don't write trigger in mysql)
CREATE TRIGGER test BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
DECLARE newClanId integer;
DECLARE counts integer;
Set #newClanId = NEW.Clanid;
Set #count := (SELECT count (*) FROM table_name
WHERE Clanid = #newClanId and Active =1)
IF #count > 1 THEN ROLLBACK;
END;

Trigger that validates line item amounts when updating a table in MySql

I am working on a lab for school which states: "Create a trigger named products_before_update that checks the new value for the discount_percent column of the Products table. This trigger should raise an appropriate error if the discount percent is greater than 100 or less than 0.
If the new discount percent is between 0 and 1, this trigger should modify the new discount percent by multiplying it by 100. That way, a discount percent of .2 becomes 20.
Test this trigger with an appropriate UPDATE statement."
My script updates the discount percent column successfully, however the "If, Then" portion does not seem to be accomplishing anything. IF I input a discount percent over 100, it does not show any errors and simply updates it. Same issue if my discount percent is less than zero. Also, if I input a number from 0-1 then it is not multiplying it by 10. Any advise would be greatly appreciated!
Here is my code:
USE my_guitar_shop;
DROP TRIGGER IF EXISTS products_before_update;
DELIMITER //
CREATE TRIGGER products_before_update
BEFORE UPDATE ON Products
FOR EACH ROW
BEGIN
DECLARE discount_percent_amount INT;
SELECT discount_percent
INTO discount_percent_amount
FROM Products
WHERE product_id = NEW.product_id;
IF discount_percent_amount > 100 THEN
SIGNAL SQLSTATE 'HY000'
set message_text =
'the discount percent cannot be greater than 100';
ELSEIF discount_percent_amount < 0 THEN
SIGNAL SQLSTATE 'HY000'
set message_text =
'the discount percent cannot be less than 0';
ELSEIF discount_percent_amount < 1 THEN
SET discount_percent_amount = (discount_percent * 10);
END IF;
END//
DELIMITER ;
UPDATE Products
SET discount_percent = .4
WHERE product_id = 3;
SELECT * FROM products;
I ended up getting it, thanks for your tip....
USE my_guitar_shop;
DROP TRIGGER IF EXISTS products_before_update;
DELIMITER //
CREATE TRIGGER products_before_update
BEFORE UPDATE ON Products
FOR EACH ROW
BEGIN
IF NEW.discount_percent > 100 THEN
SIGNAL SQLSTATE 'HY000'
set message_text =
'the discount percent cannot be greater than 100';
ELSEIF new.discount_percent < 0 THEN
SIGNAL SQLSTATE 'HY000'
set message_text =
'the discount percent cannot be less than 0';
ELSEIF NEW.discount_percent < 1 THEN
SET NEW.discount_percent = (NEW.discount_percent * 100);
END IF;
END//
DELIMITER ;
UPDATE Products
SET discount_percent = .4
WHERE product_id = 3;