Tomas Tomas - 1 year ago 67
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

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


$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
statements and
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.


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

Answer Source

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"'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download