I want to create a database query string which should be like this,
(SELECT COUNT(*) FROM states WHERE country_id = 121 ) +
(SELECT COUNT(*) FROM cities WHERE country_id = 121 ) +
(SELECT COUNT(*) FROM areas WHERE country_id = 121) +
(SELECT COUNT(*) FROM states WHERE country_id = 122) +
(SELECT COUNT(*) FROM cities WHERE country_id = 122) +
(SELECT COUNT(*) FROM areas WHERE country_id = 122)
for that i have used the code like this.
$id = array('121','122');
$table = array('states','cities','areas');
$loopCount = count($id) * count($table);
$queryString = array();
for($i=0;$i<$loopCount;$i++)
{
$queryString[] = "(SELECT COUNT(*) FROM $table[$i] WHERE country_id = $id[$i] ) + ";
}
i know the above code is totally wrong, what will be the correct way to implement the code to get desired result?
Update :
i would like to get the total number of counts From country_id not individual, that can exist in 1 to three tables, the below query seems to work fine for me, but please do let me know if you have a better solution
SELECT(
(SELECT COUNT(*) FROM states WHERE country_id IN(121,122)) +
(SELECT COUNT(*) FROM cities WHERE country_id IN(121,122) ) +
(SELECT COUNT(*) FROM areas WHERE country_id IN(121,122) )
);
EXPLAIN. I'd be surprised if this'd be efficient.