加入多个关系表

时间:2016-08-04 05:06:42

标签: php mysql join left-join

我有餐桌食物

food_id     food_name  

  1           chappathi

和另一个表类别

category_id    category_name

  1              non-veg
  2              nutrition

和关系表food_category

food_id    category_id

  1          1
  1          2

其中food_id是食物表中food_id的foriegn键,category_id是类别表中category_id的foriegn_key,没有食物类别 我试过了

 $sql=      "SELECT * FROM food f
            LEFT JOIN food_category fc
            ON f.food_id=fc.food_id
            LEFT JOIN category c
            ON fc.category_id=c.category_id"

它给了我不止一种食品,我想要的是

item name: chappathi
categories: non-veg, nutrition
------------------------------
second row of result set if there is any

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT f.food_name AS item_name,  GROUP_CONCAT(c.category_name SEPARATOR ', ') AS categories
FROM food f
LEFT JOIN food_category fc ON f.food_id=fc.food_id
LEFT JOIN category c ON fc.category_id=c.category_id
GROUP BY f.id

希望它会对你有所帮助。

答案 1 :(得分:0)

你需要的是group_concat:

SELECT f.food_name, group_concat(c.category_name) AS Cat
FROM food AS f
LEFT JOIN food_category AS fc ON f.food_id = fc.food_id
LEFT JOIN category AS c ON c.category_id = fc.category_id
GROUP BY f.food_id

答案 2 :(得分:0)

答案 3 :(得分:0)

查询应如下所示,以获取食物名称及其类别列表。

 SELECT f.food_name as ItemName,  
STUFF(
         (SELECT DISTINCT ',' + c.category_name
          FROM  food 
          LEFT JOIN food_category fc on fc.food_id= food.food_id
          LEFT JOIN category c ON fc.category_id =c.category_id                        
          FOR XML PATH ('')), 1, 1, '')  AS Categories
FROM food f                    
 group by f.food_id, f.food_name

请检查出来。