Subquery in MySQL 4
Posted by Matthew Hancock at 11:03 am
Tutorials No Comments »Unfortunately, MySQL does not support a subquery until MySQL 5.0. So if you tried to use the following code:
SELECT username FROM users WHERE user_id IN (SELECT user_id FROM admins);
you would get errors. Fortunately, I have figured out a nice little work around for this problem. Using php, you can use the following code to perform a subquery type request in MySQL 4.0.
$sql = "SELECT user_id FROM admins";
$rs = mysql_query($sql);
$adminuserids = array();
while ($ra = mysql_fetch_array($rs)){
$adminuserids[] = $ra[’user_id’];
}
# Implode your array into a comma seperated string
$adminuserids = implode(’,',$adminuserids);
# Our sql with “sub query”
$sql = “SELECT username FROM users WHERE user_id IN ($adminuserids)”;
That should take care of your MySQL 4.0 subquery needs.

Recent Comments