2010-03-14 69 views
0

比方說我有一個表,列出汽車品牌或車型:連接兩個表(通過鏈接),其中一個可能會產生多個行,連成一個結果

汽車

Id | Brand 
----------- 
1 | BMW 
2 | Audi 
3 | Volvo 

而且我還有另一張鏈接功能表。
鏈接

Id | carid | featureid 
----------------------- 
1 | 1  | 1 
2 | 1  | 2 
3 | 2  | 2 
4 | 3  | 1 
5 | 3  | 2 
6 | 3  | 3 

而且我已經得到了表列出的特徵。
特點

Id | Feature 
----------- 
1 | A/C 
2 | 4WD 
3 | Heated seats 

我想列出我的頭版這些結果是這樣的:

BMW

  • 的A/C
  • 4WD

奧迪

  • 4WD

沃爾沃

  • 的A/C
  • 4WD
  • 加熱座椅

這樣做的最好/最有效的方式是什麼(使用PHP和MySQL)?


編輯: 我想我會重新設計我Cars數據庫看起來像這個:

Id | Brand | Feature 
---------------------- 
1 | BMW  | 1,2 
2 | Audi | 1 
3 | Volvo | 1,2,3 
4 | Citröen | 

然後取Features事先和PHP相結合。我想這很容易,如果我的品牌沒有功能,我就不會遇到問題。

回答

1
SELECT Cars.Brand As Brand, Features.Feature as Feature FROM Cars, Link, Features WHERE Cars.id = Link.carid AND Features.id = Link.featureid Order By Brand 

這應該是查詢,然後使用mysql_fetch_array並打印結果

<?php 
    $result=mysql_query($query); 
    $last=''; 
    while($row = mysql_fetch_array($result)){ 
    if($row['brand']!=$last) { 
      //if the previous brand is the same don't print it out 
      //otherwise save the new brand and print it out 
      $last=$row['brand']; 
      echo "<b>".$row['brand']."</b><br>"; 
      } 
    echo $row['Feature'] . "<br>";  
    } 
?> 
+0

但這隻會給我的第一個特徵,而不是所有的人,因爲我們分組,對不對?因此,我必須使用「GROUP BY功能」,然後通過PHP遍歷結果以獲得每個結果,然後再轉到下一個品牌或某個東西上?任何關於如何簡化的想法? – Eikern 2010-03-15 18:11:09

+0

哦對,我很抱歉,使用順序而不是小組,而不是使用cicle傳遞結果...我更新了帖子,現在閱讀... – Marcx 2010-03-15 18:45:10