Tomas Tomas - 13 days ago 6
MySQL Question

Query a Query - MySQL and PHP

I was recently trying to do a project*, which caused me to ask this question. Although since then I've found an alternative solution, I am still curious if what I envisioned doing is, in any way, possible.

Essentially, I am wondering if there is anyway to perform a MySQL query on a MySQL query result in php. For example:

$result = mysql_query("SELECT * FROM foo WHERE bar=".$barValue);


AND THEN, be able to perform multiple queries on
$result
:

$newResult = mysql_query("SELECT * FROM $result WHERE otherBar=".$barValue);


OR

$otherNewResult = mysql_query("SELECT * FROM $result WHERE otherOtherBar=".$barValue." ORDER BY foobar ASC");


AND so on and so forth...

I realize that I could append the original query with my new
WHERE
statements and
ORDER BY
s, but that causes my to query the database unnecessarily and it prevents me from writing more objected oriented code (because I can't pass around a result to be queried, but rather have to requery the database in every function...)

Any advice, pieces of code, frameworks, or ramblings appreciated.

*BTW, my project was having to query a large database of people for people born in certain age groups and then query those age groups for different demographics.

Edit



No, writing a custom function to query the database is not worth the object-orientation (and modifiability) it would give me

Answer

You could do a nested query in the same SQL query and keep PHP out of it:

'SELECT * FROM (SELECT * FROM foo WHERE bar="something") AS q1 WHERE q1.bar2 = "something else"'