简体   繁体   中英

MYSQL trigger to insert data into a row. based upon some criteria

I have three tables

purchase_master

+--------+---------+------------+
| autoid | user_id | package_id |
+--------+---------+------------+

user_master

+--------+---------+------+------------+-----------+
| autoid | user_id | name | user_email | user_pass |
+--------+---------+------+------------+-----------+

package_master

+-------------+----------+--------------+-----------+------------+---------------+------------+
| poster_path | overview | release_date | genre_ids | package_id | original_title| **isfree** |
+-------------+----------+--------------+-----------+------------+---------------+------------+

I want that whenever a new row is created into user_master , a trigger should fire that gets all rows in package_master where isfree = true , and populate those records along with new user_master.user_id into purchase_master table.

Example lets say package_master has 2 rows having package_id = 100 & package_id = 101, in which isfree=true so when a new record is created into user_master having user_id = C601, the purchase_master table should have 2 new entries like.

"autoid" = 10,"user_id"=C601,"package_id"=100
"autoid" = 11,"user_id"=C601,"package_id"=101

Please guide me if it is possible through mysql trigger. Else I have to do it in PHP, on form submission.

EDIT:: I am using phpmyadmin

Try something like this:

CREATE TRIGGER bi_user_master BEFORE INSERT ON user_master
  INSERT INTO purchase_master (user_id, package_id)
    SELECT NEW.user_id, pm.package_id
      FROM package_master AS pm
      WHERE isfree;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM