简体   繁体   中英

How can I combine two mysql queries into one?

I want to combine these two queries into one:

mysql_query("INSERT INTO categories (name, parent) VALUES ('$name', '$parent')");

mysql_query("UPDATE categories SET child='$child' WHERE ID = $id");

Can it be done?

Create a trigger in MySQL.

Without doing any checking on if a parent category exists, or catching exceptions the following should do the trick. Replace 'dbname' with whatever your db is.

DROP TRIGGER IF EXISTS `dbname`.`update_parent`//
CREATE TRIGGER `dbname`.`categories` AFTER INSERT ON `dbname`.`categories`
FOR EACH ROW BEGIN
UPDATE categories SET child = NEW.ID WHERE ID = NEW.parent;
END
//

When the trigger is functioning correctly, the update will get called automatically after an INSERT so all you have to do is run:

mysql_query("INSERT INTO categories (name, parent) VALUES ('$name', '$parent')");

尽管我不知道这是否适合您的问题,但实际上可以通过使用MySQLi扩展将多个查询合并为一个(不适用于mysql扩展)

mysqli_multi_query($connection, "INSERT INTO a (attrib1, attrib2) VALUES ('$a', '$b');UPDATE b SET attrib3='$c' WHERE attrib4 = $d");

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