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 />'; }