2010-03-14 66 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