简体   繁体   中英

Combine the two queries into one that needs a value from second query in first

I have two SQL queries:

$res1 = mysql_query("SELECT * FROM `table1` WHERE `user`='user'");
$i = mysql_fetch_assoc($res1);    
$value1 = $i['num'];

And:

$res2 = mysql_query("INSERT INTO `table2` (`name`,`num`) VALUE ('name','$value1')");

How to combine the two SQL queries into one? I need to get the value of the variable from of a second query for the first request. Is it possible?

This query with a subquery should do the trick nicely for you:

insert into table 2 (`name`, `num`) 
    values ('name', (select `num` from table1 where `user`='user'));

This assumes that you aren't using anything but the num from your second query as it doesn't seem to be used in your original code.

Edit: Also, I see that this is an insert, not just a select statement, but you might well benefit from reading a rather lengthy question and answer I put up which covers off multiple tables and SQL covering unions, joins, subqueries and a bunch more stuff.

Can you use the INSERT INTO ... SELECT ... syntax?

Eg something like:

INSERT INTO table2 (name, num)
SELECT 'name', num
FROM table1
WHERE user='user' 

(untested so please forgive any minor errors here...)

Scrap this.

The best answer is to have PHP have the data that MYSQL is going to need. Doing it any other way will cause bottlenecks and is inefficient.

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