INSERT and SELECT together in one statement

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

INSERT and SELECT together in one statement

Post by superdezign »

Is it possible to do something like this:

Code: Select all

INSERT INTO `newFeature` (`userid`, `data`, ...) VALUES((SELECT `id` FROM `users` WHERE `username` = '$username' AND `password` = '$password'), $data, ...);
... without doing the select statement separately?


It's not crucial or anything... I've already got a way around it. I'm just curious.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Yes, it is totally possible. Need MySQL >= 4.1

http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

I have MySQL 5, and I can't use subqueries with the INSERT statement. Using them in a SELECT statement, however, work's fine.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

You're looking for this
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

^_^

Thank ya.
Post Reply