Mar 9, 2010

nested select statements

problem
i came across this while trying to put together a complex sql query that would find specific items within a data set. at first i did this by writing a query and pulling the info into an array in php. then creating a data set from that to build another query from:

$sql = "SELECT * FROM table WHERE column = value";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result) {
	if ($row["column"] == "some value") $array[] = $row;
}
$sql = "SELECT * FROM table WHERE column IN (".implode(",",$array).")";
$result = mysql_query($sql);

solution
you can see how having to do this a few times can become rather tedious to hone in on a small data set. as of MySQL 5, however, you can nest SELECT statements to produce very complex queries that can help narrow down your result:

SELECT model
FROM cars
WHERE make IN (
	SELECT *
	FROM automakers
	WHERE automaker = "Honda"
	)

conclusion
while this is only a simple representation of the capabilities, you can see how nesting a few SELECT statements can reduce the number of subsequent queries you need to make in order to get the result set that you desire.

Leave a comment