PHP MySQL在多个表上选择查询

时间:2012-10-20 06:39:48

标签: php mysql select join

这可能吗?如果是这样,我如何构造我的SELECT语句来实现这些结果?

我在PHP文件中创建一个HTML表,从MySQL数据库中获取各种行。这是我的问题:

     // Define the query:
     $query = "SELECT b.birdID, b.nameGeneral, b.nameSpecific, 
               b.genus, b.species, b.family, b.populationTrend, f.food, h.habitat 
               FROM bird_habitat AS bh 
               JOIN bird_food AS bf ON (bf.birdID_FK = bh.birdID_FK) 
               JOIN food AS f ON (f.foodID = bf.foodID_FK) 
               JOIN habitat AS h ON (h.habitatID = bh.habitatID_FK) 
               JOIN birds AS b ON (b.birdID = bh.birdID_FK AND b.birdID = bf.birdID_FK) 
               ORDER BY b.birdID ASC";

问题在于bird_habitat和bird_food表。每只鸟可以吃2种不同的食物,也可以在2个不同的栖息地生活。例如,黑鹂可以吃种子和昆虫,生活在沼泽和田野中。当我运行SELECT语句时,每只鸟得到4个结果,我只想获得2个结果。使用blackbird示例,我返回了这些行:

**Bird**  **Food**       **Habitat**
    1       Seeds          Marsh
    1       Insects        Marsh
    1       Seeds          Field
    1       Insects        Field

我想要归还的是:

**Bird #**  **Food**       **Habitat**
    1         Seeds          Marsh
    1         Insects        Field

所以基本上,我想要回报每只鸟可以吃的独特食物以及它们可以居住的独特栖息地,而不会重复多余的田地。这可能吗?如果是这样,我如何构造我的SELECT语句来实现这些结果?

如果您想查看上面的SELECT查询返回的内容,以下是显示HTML表的页面的链接,以便您可以更好地了解我要执行的操作:

http://www.jasonkmccoy.com/AB-Tech/web250/Mod07/McCoy_edit_delete/index.php

正如您将看到的那样,如果您访问有2种食物和2种栖息地的鸟类,我需要删除2行,以便只返回唯一的字段。

1 个答案:

答案 0 :(得分:0)

"SELECT b.birdID, b.nameGeneral, b.nameSpecific, 
b.genus, b.species, b.family, b.populationTrend, f.food, h.habitat 
FROM birds  
JOIN bird_food AS bf ON (bf.birdID_FK = bh.birdID_FK) 
JOIN food AS f ON (f.foodID = bf.foodID_FK) 
JOIN habitat AS h ON (h.habitatID = bh.habitatID_FK) 
JOIN bird_habitat AS bh  ON (b.birdID = bh.birdID_FK ) 
group by f.foodID
ORDER BY b.birdID ASC";