I have to adapt a PHP-script that is connected to a extremely messy database-design.
The best way to explain the problem is to post the code, within which im going to describe whats happening through comments inside the code-block. Plus a short introduction:
Short Story:
1.) There is a "mainQuery" and inside the for-loop that displays its data there are 3 nested subqueries.
2.) All three subqueries need the main_table_ID in order to count the occurences of each fetched_row.
What i want:
1.) An optimzied mainQuery that counts 3 occurences of an id separately on its own.
2.) Thus no subqueries at all inside the for loop.
What i have already achieved via optimizing the mainQuery:
1.) I can filter a subquery one at a time by, see statement:
SELECT
main_table.id_col,
count(table_1.a_col) AS count_1,
main_table.a_col,
main_table.b_col,
main_table.c_col,
main_table.d_col,
main_table.e_col
FROM main_table
LEFT JOIN
table_1
ON
table_1.a_col = main_table.id_col
GROUP BY
main_table.id_col
But when i add another LEFT JOIN for the one of other nested statements inside the for-loop, the statement sums everything up and count_1 to count_3 look the same.
And now the code-block containing the subqueries and the for-loop:
<?php
$mainQuery = "SELECT
main_table.id_col,
main_table.a_Col,
main_table.b_Col,
main_table.c_col,
main_table.d_col,
main_table.e_col
FROM
main_table";
$mainQueryResult = mysql_query($mainQuery);
$mainQueryRows = mysql_num_rows($mainQueryResult);
for($j = 0 ; $j < $mainQueryRows ; ++$j){
//mainQuery data
$mainQueryRow = mysql_fetch_row($mainQueryResult);
$main_table_ID = $mainQueryRow[0];
//first subquery, can be filtered out one at a time
//using introductory-statement
$count_1_subQuery = "SELECT * FROM table_1
WHERE table_1.id_col = '$main_table_ID'";
//first subquery-count of rows with matching id
$count_1 = mysql_num_rows(mysql_query($count_1_SubQuery, $connection));
//second subquery
$count_2_subquery = "SELECT * FROM table_2
WHERE table_2.id_col = '$main_table_ID'";
//second subquery-count of rows with matching id
$count_2 = mysql_num_rows(mysql_query($count_2_subQuery, $connection));
//third subquery
$count_3_subquery = "SELECT * FROM table_3
WHERE table_3.id_col = '$main_table_ID'";
//third subquery-count of rows with matching id
$count_3 = mysql_num_rows(mysql_query($count_3_subQuery, $connection));
//Fill Table with count_1 to count_3
//and main_table.a_col to main_table.e_col
//no problems here
}
?>
I hope i could explain the problem clearly enough and i also hope one of you guys can help me, if he/she can allot time for such a question.