MySQL before insert trigger that drops insert if condition

MySQL before insert trigger that drops insert if condition

I have the following tables:

I have the following tables:


|    id     | sld_name  |  
|     1     |  google   |  
|     2     |  github   |


|    id     | path_name  |  sld_id  |   
|    101    |  /cats/    |    1     |
|    102    |  /dogs/    |    2     |

Note that the sld_name is a unique index, and sld_id is the foreign key of slds.

INSERT IGNORE INTO paths (path_name, sld_id)
VALUES ('/dogs/', 1), ('/dogs/', 2) ... this can be hundreds of rows long

When the example above happens, I need a way to remove/prevent the insert of the additional ('/dogs/', 2) row, since that path already exists where sld_id=2, and not prevent the ('/dogs/', 1) row, since sld_id=1 doesn't have a /dogs/ path yet.

To implement this, I tried using this trigger:

delimiter $$
create trigger after_insert_paths
after insert on paths 
for each row begin
declare path_check INT;

set path_check := ( select sld_id from paths where path_name=new.path_name and sld_id=new.sld_id ); if path_check is not null then set new.path_name = null; end if;

end $$ delimiter ;

All this did was prevent inserts from happening at all.

Is there something specific that is wrong with the trigger? or does this strategy not work in general?

Is there a better approach to this that I'm missing?

Any advice would really be appreciated! :)

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

What are the differences between Standard SQL and Transact-SQL?

In this article, we'll explain syntax differences between standard SQL and the Transact-SQL language dedicated to interacting with the SQL

SQL Full Course - SQL Tutorial For Beginners - MySQL Essentials - SQL Training

This SQL Full Course video will cover all the topics of SQL starting from scratch. This video is great for beginners who want to learn SQL and for advanced people to brush up their skills.