What I'm trying to achieve is, I want to automate the values of the table between the users and folders table. Since it's a many-to-many relationship I created the user_folders table. Currently the server (nodejs) gets the request with userid, clientfolderid and some an array of bookmarks (which are not important now). It checks if the user already has this folder, by selecting from the user_folders table and if it's not existing it inserts a new row into the folder table. Then it has to send another statement to insert into the user_folders table.
So I have to "manually" keep the users_folder table updated.I guess this is a common problem and wanted to know if there is a pattern or a proven solution? The odd thing is that MySQL automatically handles the deletion of rows with an AFTER DELETE trigger but there is no (at least that I know of) automation with an AFTER INSERT trigger.
As I already said an AFTER INSERT trigger could possibly solve it, but I think it's not possible to pass some extra parameters to the AFTER INSERT trigger. This would be the user_id and the folder_client_id in my case.
I was thinking of a solution that I could create another table called tmp_folder which would look like:
tmp_folder
-- id
-- title
-- changed
-- user_id
-- folder_client_id
Then create an AFTER INSERT trigger on this table which inserts into folders and user_folders and then removes the row from tmp_folder again. Would this be the right way or is there a better one?
I would basically do the same with the bookmarks and user_bookmarks table. The best thing would be if it's even possible to insert a folder then the owner into the user_folders table with user_id and folder_client_id and then multiple other users into user_folders with the user_id and an default folder_client_id of -1 or something which will be updated later.
Meanwhile thanks for reading and I hope you can help me :)
PS: Is there a name for the table between 2 other tables in an m-2-m relationship?
I don't see an easy way to do this via triggers, but a stored procedure may suit you:
DELIMITER //
CREATE PROCEDURE
add_user_folder(
IN u_user_id BIGINT UNSIGNED,
IN u_folder_client_id BIGINT UNSIGNED,
IN v_title VARCHAR(255)
)
BEGIN
DECLARE u_found INT UNSIGNED DEFAULT 0;
SELECT
1 INTO u_found
FROM
user_folders
WHERE
user_id = u_user_id AND
folder_client_id = u_folder_client_id;
IF IFNULL(u_found, 0) = 0 THEN
START TRANSACTION;
INSERT INTO
folders
SET
title = v_title,
changed = UNIX_TIMESTAMP();
INSERT INTO
user_folders
SET
user_id = u_user_id,
folder_id = LAST_INSERT_ID(),
folder_client_id = u_folder_client_id;
COMMIT;
END IF;
END;
//
Related
At a high level I am already aware that you can not insert a new row to the same table and that one should consider a SPROC. Here is the use case though. There is a 3rd party web app and this MySQL DB that I have, so I have no control over the application flow. A request has come in to simplify data entry. What I do have control over is the database. The app is like a CRM and has a contacts table and there is a 2nd contact_relationships table where I am putting the trigger on. Basically the contact_relationships needs three fields. Two contactIDs (INT) from the contact table and a relationship_type varchar(45) like (Spouse, Sibling, External Family and so on).
The goal here is when a new row is added (the TRIGGER) to the contact_relationships table, that we ALSO write a 2nd row to the SAME TABLE that inverts the contactIDs and keeps the relationship_type. This ensures there is also a record relationship established for the other contact from the same single entry. (ideally should be done in the app).
I'm at my whits end over what should be a stupid simple operation. I even tried this creative implementation.
I created a new _temp table
CREATE TABLE `_temp` (
`id_temp` int(11) NOT NULL AUTO_INCREMENT,
`Contact_id` int(11) DEFAULT NULL,
`Relation_id` int(11) DEFAULT NULL,
`Relationship_Type` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id_temp`)
I have two triggers on the contact_relationships table
#1
CREATE DEFINER=`root`#`localhost` TRIGGER `contact_relationships_BEFORE_INSERT` BEFORE INSERT ON `contact_relationships` FOR EACH ROW BEGIN
insert into _temp (Contact_id,Relation_id,Relationship_Type)
values(NEW.Contact_id,NEW.Relation_id,NEW.Relationship_Type);
END
#2
CREATE DEFINER=`root`#`localhost` TRIGGER `contact_relationships_AFTER_INSERT` AFTER INSERT ON `contact_relationships` FOR EACH ROW BEGIN
delete from _temp;
END
On the _temp table I have this trigger
CREATE DEFINER=`root`#`localhost` TRIGGER `_temp_AFTER_DELETE` AFTER DELETE ON `_temp` FOR EACH ROW BEGIN
#DO Sleep(2);
# Sleep commented out as it did not work and only delayed the error
insert into contact_relationships (Relation_id,Contact_id,Relationship_Type) values(OLD.Contact_id,OLD.Relation_id,OLD.Relationship_Type);
END
So my thinking here in pseudo code is like this
When a row is inserted into the contact_relationships table write the inverted row to a temp table as I can not write it to the **same table from inside the trigger**.
AFTER the triggered inserted row is complete lets delete the row in the temp table so we can create a DELETE trigger on that other table to write the desired row into the contact_relationship.
At this stage I believe the TRIGGER and TRANSACTIONS on the contact_relationships table are DONE
On the temp Table a trigger and transaction firing AFTER any contact_relationships transactions
Results are maddening and always the same albeit internal or external. I have tried creative functions and sprocs all with the same aggravating results.
Contact Relationships : Add New
Can't update table 'contact_relationships' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Query:
insert into `Contact_Relationships` set `Contact_id`='2', `Relation_id`='3', `Relationship_Type`='Extended Family'
I'm completely brain dead on how I may accomplish this - anyone have a way to pull this off?
dsoden.
What I would do is:
Inside the trigger definition, you can get the "inserted_id" of the relationship that was inserted ( You can get it withLAST_INSERT_ID() ).
Once you have it, you can SELECT from that record into temp variables:
SELECT `Contact_id`,`Relation_id`,`Relationship_Type` INTO #cont_id, #rel_id, #rel_type
FROM contact_relationships
WHERE id = LAST_INSERT_ID()
And then do the Insert of the new relationship in the reverse order, with the same relationship type:
INSERT INTO contact_relationships (`Contact_id`,`Relation_id`,`Relationship_Type`) VALUES ( #rel_id, #cont_id, #rel_type);
If that's what you're aiming for..
Something like:
When a relationship between Anne and John as Siblings is inserted,
insert the John,Anne,Siblings relationship as well
I'm running a wateranalyzer and want to save the sensor-data in a MariaDB.
I split the data into 2 tables: one for the automated part and one table which stores data I enter manually:
Tables:
I'm having a hard time (with just basic knowledge about databases) to figure out how I can "bind" ID and DateTime from one table to the other one, so if manual data is added, ID is incremented by 1 and the actual Date and Time is set in DateTime.
I bet I can do this somehow in PHPmyadmin?
thanks for your time!
using triger. this example for you.
DELIMITER //
CREATE TRIGGER contacts_after_insert
AFTER INSERT
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing the INSERT into table
SELECT USER() INTO vUser;
-- Insert record into audit table
INSERT INTO contacts_audit
( contact_id,
deleted_date,
deleted_by)
VALUES
( NEW.contact_id,
SYSDATE(),
vUser );
END; //
DELIMITER ;
Is it anything more complex than having an ID in Wasser that matches the other ID? That is, first insert into Luft, then get the id and only then, INSERT INTO Wasser....
(A Trigger seems unnecessarily complicated.)
As Rick Suggested, you need to have an ID column in the second table that references ID in first table. Trigger is a better option if the process of getting the ID and inserting it along with other columns (pH, Redox...) into the second table is complicated.
Make ID in the second table as a foreign key to the ID in first table.
I need to insert a discount line into a table everything time a I insert a line into the same table.
Now i know that this could end in a endless loop but I have put checks in so it wont insert anything when the discount line is inserted.
Mysql doesnt seem to allow this.It doesnt even insert into the table let alone fire off the trigger
Any suggestions on how to do this?
You cannot alter a table (other than the current row) in a trigger attached to that table.
One solution is to insert into another table and have that trigger insert 2 rows into the table you're interested in.
If you make the other table a blackhole you don't have to worry about storage.
DELIMITER $$
CREATE TRIGGER ai_bh_test_each AFTER INSERT ON bh_test FOR EACH ROW
BEGIN
INSERT INTO table1 (field1, field2, ...) VALUES (new.field1, new.field2, ....);
INSERT INTO table1 ... values for the second row
END $$
DELIMITER ;
Why don't you just change your INSERT code into something like this? :
INSERT INTO table1 (field1, field2, ...)
VALUES ( #item, #price, ....)
, ( #item, #discount, ...) ;
Another thing would be to re-evaluate your data structure. The way it is now, it seems - from the limited information you have provided - that it's not normalized. You are storing two types of info in the table.
Perhaps you can combine the two rows (that are to be inserted every time) into one, by adding a few columns in the table.
Or by splitting the table into two tables, one for the "normal" item rows and one for the discount items.
It isn't allowed in MySQL.
One solution would be to let the trigger insert two times into another table. Then you would do writes and updates to the write table and reads from the trigger managed read table.
I needed to add an additional row to the same table, based on a specific condition on an aggregate of the table and was unable to update my application queries to handle it outside of the database, due to stability lock policy.
An alternative solution is to utilize Events in MySQL to read a "staging" table that holds the pending changes. This works by eliminating the circular reference that would be caused by the trigger. The event then executes the desired changes, without initiating the trigger, by using a session variable to leave the trigger early. Please modify the event timing to suit your needs, such as EVERY 5 SECOND.
Staging Table
CREATE TABLE `table_staging` (
`id` INT NOT NULL,
`value` VARCHAR(250) NOT NULL,
`added` TINYINT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
Trigger
CREATE TRIGGER `table_after_insert` AFTER INSERT ON `table` FOR EACH ROW
tableTrigger: BEGIN
IF #EXIT_TRIGGER IS NOT NULL THEN
/* do not execute the trigger */
LEAVE tableTrigger;
END IF;
/* insert the record into staging table if it does not already exist */
INSERT IGNORE INTO `table_staging`(`id`, `value`)
VALUES (NEW.id, 'custom value');
END;
Event
CREATE EVENT `table_staging_add`
ON SCHEDULE
EVERY 1 MINUTE STARTS '2020-03-31 18:16:48'
ON COMPLETION NOT PRESERVE
ENABLE
COMMENT ''
DO BEGIN
/* avoid executing if the event is currently running */
IF #EXIT_TRIGGER IS NULL THEN
SET #EXIT_TRIGGER=TRUE;
/* add the values that have not already been updated */
INSERT INTO table(`value`)
SELECT
ts.value
FROM table_staging AS ts
WHERE ts.added = 0;
/* update the records to exclude them on the next pass */
UPDATE table_staging AS ts
SET ts.added = 1;
/* alternatively remove all the records from the staging table */
/* TRUNCATE table_staging; */
/* reset the state of execution */
SET #EXIT_TRIGGER=NULL;
END IF;
END;
Notes
Be sure to enable the event scheduler in your MySQL configuration (my.ini on Windows or my.cnf on Linux).
[mysqld]
event_scheduler = ON
I have one table: drupal.comments, with amongst others, the columns:
cid: primary key
uid: foreign key to users table, optional
name: varchar, optional
email: varchar, optional
The description says: UID is optional, if 0, comment made by anonymous; in that case the name/email is set.
I want to split this out into two tables rails.comments and rails.users, where there is always a user:
id: primary key
users_id: foreign key, always set.
So, for each drupal.comment, I need to create either a new user from the drupal.comments.name/drupal.comments.email and a rails.comment where the rails.comment.users_id is the ID of the just created user.
Or, if username/email already exists for a rails.user, I need to fetch that users_id and use that on the new comment record as foreign key.
Or, if drupal.comment.uid is set, I need to use that as users_id.
Is this possible in SQL? Are queries that fetch from one source, but fill multiple tables possible in SQL? Or is there some (My)SQL trick to achieve this? Or should I simply script this in Ruby, PHP or some other language instead?
You could do this with a TRIGGER.
Here's some pseudo-code to illustrate this technique:
DELIMITER $$
DROP TRIGGER IF EXISTS tr_b_ins_comments $$
CREATE TRIGGER tr_b_ins_comments BEFORE INSERT ON comments FOR EACH ROW BEGIN
DECLARE v_uid INT DEFAULT NULL;
/* BEGIN pseudo-code */
IF (new.uid IS NULL)
THEN
-- check for existing user with matching name and email address
select user_id
into v_uid
from your_user_table
where name = new.name
and email = new.email;
-- if no match, create a new user and get the id
IF (v_uid IS NULL)
THEN
-- insert a new user into the user table
insert into your_user_table ...
-- get the new user's id (assuming it's auto-increment)
set v_uid := LAST_INSERT_ID();
END IF;
-- set the uid column
SET new.uid = v_uid;
END IF;
/* END pseudo-code */
END $$
DELIMITER ;
I searched further and found that, apparently, it is not possible to update/insert more then one table in a single query in MySQL.
The solution would, therefore have to be scripted/programmed outside of SQL.
Is it possible to enforce uniqueness across two tables in MySQL?
I have two tables, both describing users. The users in these tables were for two different systems previously, however now we're merging our authentication systems and I need to make sure that there are unique usernames across these two tables. (it's too much work to put them all into one table right now).
You can't declare a UNIQUE constraint across multiple tables. MySQL 8.0 supports CHECK constraints, but those constraints cannot reference other tables. But you can design a trigger to search for the matching value in the other table. Here's a test SQL script:
DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (username VARCHAR(10) NOT NULL);
DROP TABLE IF EXISTS bar;
CREATE TABLE BAR (username VARCHAR(10) NOT NULL);
DROP TRIGGER IF EXISTS unique_foo;
DROP TRIGGER IF EXISTS unique_bar;
DELIMITER //
CREATE TRIGGER unique_foo BEFORE INSERT ON foo
FOR EACH ROW BEGIN
DECLARE c INT;
SELECT COUNT(*) INTO c FROM bar WHERE username = NEW.username;
IF (c > 0) THEN
-- abort insert, because foo.username should be NOT NULL
SET NEW.username = NULL;
END IF;
END//
CREATE TRIGGER unique_bar BEFORE INSERT ON bar
FOR EACH ROW BEGIN
DECLARE c INT;
SELECT COUNT(*) INTO c FROM foo WHERE username = NEW.username;
IF (c > 0) THEN
-- abort insert, because bar.username should be NOT NULL
SET NEW.username = NULL;
END IF;
END//
DELIMITER ;
INSERT INTO foo VALUES ('bill'); -- OK
INSERT INTO bar VALUES ('bill'); -- Column 'username' cannot be null
You also need similar triggers ON UPDATE for each table, but you shouldn't need any triggers ON DELETE.
the best way to do this is to declare another table with the unique columns, and have the multiple tables reference these tables
Maybe not direct answer to your question, but:
You should consider rewriting your code and restructuring your database to unite those two tables into one.
The design you are trying to enforce now will complicate your code and database schema and it will make any further upgrade to other database software or frameworks harder.
You could add an extra table with a single column as a primary key. Then create a trigger on each of your old user tables to insert the id into this extra table.
create table users1 (
user_id integer primary key,
username varchar(8) not null unique
);
create table users2 (
user_id integer primary key,
username varchar(8) not null unique
);
create table all_usernames (
username varchar(8) primary key
);
create trigger users1_insert before insert on users1 for each row
insert into all_usernames values(new.username);
create trigger users2_insert before insert on users2 for each row
insert into all_usernames values(new.username);
create trigger users1_update before update on users1 for each row
update all_usernames set username = new.username
where username = old.username;
create trigger users2_update before update on users2 for each row
update all_usernames set username = new.username
where username = old.username;
create trigger users1_delete before delete on users1 for each row
delete from all_usernames where username = old.username;
create trigger users2_delete before delete on users2 for each row
delete from all_usernames where username = old.username;
You can then populate the table with
insert into all_usernames select username from users1;
insert into all_usernames select username from users2;
Obviously if there are already duplicates in the two tables you will have to solve that problem by hand. Moving forward, you could write a trigger that checks both tables to see if the value already exists, and then apply that to both tables.
Would changing the type of the ID column be affordable? Then you could go for GUIDs which would be unique across as many tables as you want.
I don't know MySQL but this is how you can do it in Oracle and I believe MySQL does support materialized views too.
You create a materialized view on those two tables. And you add a unique constraint on this view.
This view needs to be refreshed every time a change to one of the two base tables is committed.