0

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

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

     // 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 行以便只返回唯一的字段。

4

1 回答 1

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";
于 2012-10-20T06:53:47.660 回答