是否可以插入一行并在同一查询中插入值?
就像是…
INSERT INTO `items` (`item`, `number`, `state`) (SELECT '3', `number`, `state` FROM `item_bug` WHERE `id`='3')
然后,获取ID并执行
SELECT * FROM `items` WHERE `id`='$id'
但是只使用一个查询。
您可以调用存储过程,该过程将执行插入操作,并在一次调用中将结果集从应用程序层返回到mysql:
存储过程调用
mysql> call insert_user('bar'); +---------+----------+ | user_id | username | +---------+----------+ | 1 | bar | +---------+----------+ 1 row in set (0.02 sec) $sqlCmd = sprintf("call insert_user('%s')", ...);
简单的例子:
drop table if exists users; create table users ( user_id int unsigned not null auto_increment primary key, username varchar(32) unique not null ) engine=innodb; drop procedure if exists insert_user; delimiter # create procedure insert_user ( in p_username varchar(32) ) begin declare v_user_id int unsigned default 0; insert into users (username) values (p_username); set v_user_id = last_insert_id(); -- do more stuff with v_user_id e.g. logs etc... select * from users where user_id = v_user_id; end# delimiter ; call insert_user('bar');