There is a data output from the table. I would like to know, nothing, that in the loop itself when outputting records from the support table , is the function used to output a count of comments (get__num__comments) , in which 1 query to the database? Is it correct?

// функция вывода кол-ва комментариев function get_num_comments($id) { $query = mysql_query("SELECT * FROM `support_comments` WHERE `support_id` = '$id'"); return mysql_num_rows($query); } // выводим записи из таблицы support $query = mysql_query("SELECT * FROM `support`"); while($data = mysql_fetch_array($query)) { echo get_num_comments($data['id']); // получаем кол-во комментариев к каждой записи } 

    2 answers 2

    Querying in a loop is generally a bad idea. In this case, one request of the form is sufficient:

     select support.*, count(support_comments.id) as num_comments from support left join support_comments on support.id=support_comments.support_id group by support.* 

    where there are asterisks, list (both in select and in group by) the required fields.

    Threat mysql allows you not to write group by, but this is for those people who know what is coming back, and not for those who are too lazy to write the list of fields from select.

    • Um, I didn’t guess how to combine both) to Plyusan) - Sh4dow

    The bad option: firstly, there is no need to take all the data from the table; secondly, requests can be combined:

     // примерная функция (мб сразу будет работать) function get_num_comments_all($ids = array()) { if (empty($ids)) return array(); $result = array(); $q = mysql_query(' SELECT `support_id`, COUNT(`support_id`) AS Count FROM `support_comments` WHERE `support_id` IN ('.implode(', ', $ids).') GROUP BY `support_id`; '); while ($rec = mysql_fetch_object($q)) $result[$rec->support_id] = $rec->Count; return $result; // массив в формате support_id => Count } // далее собираем id $ids = array(); $items = array(); $query = mysql_query("SELECT * FROM `support`"); while($data = mysql_fetch_object($query)) { $items []= $data; // собираем массив записей $ids []= $data->id; // и отдельно айди } // получаем кол-во комментов для всех записей $comment_sum = get_num_comments_all($ids); // вывод foreach ($items as $item) { echo $item->id.': '.$comment_sum[$item->id].'<br />'; }