2012-06-16 33 views
0

是否可以使用一個SQL查詢來實現?任何改進?(嵌套的MySQL語句)是否可以使用一個SQL查詢來實現?任何改進?

$query = mysql_query("SELECT id, name FROM fruits WHERE `group`=''"); 

if ($query) { 
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) { 
     echo $row['name']; 

     $query2 = mysql_query("SELECT name FROM fruits WHERE `group`='{$row['id']}'"); 

     if (mysql_num_rows($query2)) { 
      echo ':'; 

      while ($row2 = mysql_fetch_array($query2, MYSQL_ASSOC)) { 
       echo ' '. $row2['name'] . ','; 
      } 
      mysql_free_result($query2); 

      echo '<br>'; 
     } 
    } 
    mysql_free_result($query); 
} 

結果:

Berries: blueberry, raspberry, strawberry, 
Citrus: grapefruit, lime, 
Pear 

數據庫結構SELECT * FROM fruits

id | group | name 
------------------------- 
03E7 |  | Berries 
0618 | 03E7 | blueberry 
051B | 03E7 | raspberry 
02AA | 03E7 | strawberry 
035F |  | Citrus 
07A5 | 035F | grapefruit 
0633 | 035F | lime 
05E1 |  | Pear 
+1

通常你會用自聯接做到這一點。 – Amber

回答

0

工作的完整示例:

<?php 

header("Content-Type: text/plain"); 

$con = mysql_connect("localhost", "root", ""); 
mysql_select_db("test"); 

$query = mysql_query("SELECT a.name as `group`, GROUP_CONCAT(b.name ORDER BY b.name SEPARATOR ', ') as name FROM fruits a LEFT JOIN fruits b ON b.`group` = a.id WHERE a.`group` = '' GROUP BY a.name"); 

if ($query) { 
    while ($row = mysql_fetch_array($query)) { 
     $group = $row['group']; 
     $name = $row['name']; 

     if (isset($name)) { 
      echo $group . ': ' . $name . "\n"; 
     } else { 
      echo $group . "\n"; 
     } 
    } 
    mysql_free_result($query); 
} 
mysql_close($con); 

?> 

結果:

Berries: blueberry, raspberry, strawberry 
Citrus: grapefruit, lime 
Pear 
5
SELECT a.name as group_name, b.name as item_name 
FROM fruits a 
LEFT JOIN fruits b 
ON b.`group` = a.id 
WHERE a.`group` = '' 

將讓你一組結果行,看起來像的......

group_name item_name 
---------------------- 
Berries  blueberry 
Berries  raspberry 
...   ... 
Citrus  grapefruit 
Citrus  lime 
...   ... 
Pear   NULL 

然後你可以在你的代碼中處理這個來產生你想要的任何最終輸出。

+0

到目前爲止,與SQL,但如何與PHP的結果? – Binyamin

+0

你有什麼嘗試? StackOverflow不是一個讓人們爲你編寫所有代碼的網站。 – Amber

+0

這是我嘗試http://stackoverflow.com/questions/11043558/how-to-implement-mysqli-nested-prepared-statements#comment14451252_11043558,但它在第二個'準備'語句中返回了一個非對象錯誤。 – Binyamin

相關問題