使用php将数据合并到一列mysql中

时间:2015-01-26 06:44:06

标签: php mysql

美好的一天我正在为食谱建立一个网站并且我试图显示具有多种成分的食谱但是成分在一个单独的表中,所以当我运行查询如果我有三个成分时,食谱ID将出现三次以及其他数据,因为成分列只有一个条目填充...无论如何要合并这些条目?

这是我的代码和链接到数据显示方式的图像。任何帮助都会很棒

[img] http://forums.trinituner.com/upload/data/62/all recipes duplicate.jpg [/ img]

我的代码     

         $db=mysql_select_db("tasteofhome");



        $query = "select RECIPES.recipe_ID,RECIPES.recipe_name,RECIPES.recipe_author,RECIPES.cook_time,RECIPES.stages_description, INGREDIENTS.ingredients_name, USERS.user_name from
        RECIPES,USERS,RECIPE_INGREDIENTS,INGREDIENTS where USERS.user_ID=RECIPES.user_ID AND
        RECIPES.recipe_ID = RECIPE_INGREDIENTS.recipe_ID
        AND RECIPE_INGREDIENTS.ingredients_ID = INGREDIENTS.ingredients_ID
        ";

        $result = mysql_query ($query);

if($result === FALSE) { 
    die(mysql_error()); // TODO: better error handling
}


        while ($rows = mysql_fetch_array ($result))
        { //begin of while loop
     ?>
        <tr>
          <td> <?php echo $rows [0]; ?>  </td>
          <td> <?php echo $rows [1]; ?> </td>
          <td> <?php echo $rows [2]; ?> </td>
          <td> <?php echo $rows [3]; ?> </td>
          <td> <?php echo $rows [4]; ?> </td>
          <td> <?php echo $rows [5]; ?> </td>
          <td> <?php echo $rows [6]; ?> </td>

        </tr>

         <?php

        } //end of while loop


         ?>

1 个答案:

答案 0 :(得分:0)

您可以将recipesusers表与一个使用group_concat的聚合查询结合起来,将成分加入到逗号分隔的字符串中:

SELECT r.recipe_ID, 
       r.recipe_name,
       r.recipe_author,
       r.cook_time, 
       r.stages_description,
       gi.ingredients_names,
       u.user_name 
FROM   RECIPES r
JOIN   USERS u ON u.user_ID = r.user_ID
JOIN   (SELECT   ri.recipe_ID,
                 GROUP_CONCAT(i.ingredients_name) AS ingredients_names
        FROM     RECIPE_INGREDIENTS ri
        JOIN     INGREDIENTS i ON ri.ingredients_ID = i.ingredients_ID
        GROUP BY recipe_ID) gi ON gi.recipe_ID = r.recipe_ID