MYSQL GROUP_CONCAT喜欢遵循顺序

时间:2018-10-05 16:18:59

标签: mysql

我有3张桌子: 第一个包含产品:

+-----+-------------+---------------+
|  ID |     NAME    | IngredientsID |
+-----+-------------+---------------+
| 01  |   Pizza     | 01,02,04      |
+-----+-------------+---------------+
| 02  |   Spagetti  | 01,02         |
+-----+-------------+---------------+
| 03  | Cheesburger | 01,04,02,03   |
+-----+-------------+---------------+
| 04  |   Nuggets   | 01,04         |
+-----+-------------+---------------+

第二个包含成分详细信息:

+-----+-------------+-------------+--------+
|  ID |     NAME    |  Allergens  | Frozen |
+-----+-------------+-------------+--------+
| 01  |   Flour     |   01        |    0   |
+-----+-------------+-------------+--------+
| 02  |   Water     |             |    0   |
+-----+-------------+-------------+--------+
| 03  |   Nuts      |  03         |    0   |
+-----+-------------+-------------+--------+
| 04  |   Fish      |  02         |    1   |
+-----+-------------+-------------+--------+

第二个包含过敏原详细信息:

+-----+-------------+-------------+
|  ID |     NAME    |  Allergens  |
+-----+-------------+-------------+
| 01  |   Flour     |   01        |
+-----+-------------+-------------+
| 02  |   Water     |             |
+-----+-------------+-------------+
| 03  |   Nuts      |  03         |
+-----+-------------+-------------+
| 04  |   Fish      |  02         |
+-----+-------------+-------------+

现在要查询,我需要为给定的Food_ID提取成分名称和Allergenes名称的列表:

,我使用了以下查询:

SELECT
    ID,
    Name,
    (
        select 
            GROUP_CONCAT(DISTINCT Name SEPARATOR ',')
        from Ingredients
        where (select IngredientsID from Products where ID=@Food_ID) 
        like concat('%',IngredientID,'%')
    ) IngredientsNames
FROM products 
WHERE ID=@Food_ID

(for allergenes Names I used a nested GROUP_CONCAT)

返回@Food_ID=03,例如:

+-----+-------------+----------------------------+
| ID  |  Name       | IngredientsNames           |
+-----+-------------+----------------------------+
| 03  | Cheesburger | Water,Flour,Fish,Nuts      |
+-----+-------------+----------------------------+

我是MYSQL的新手,我尝试使用INFIND_IN_SET运算符,但没有成功:所以我使用了LIKE: 我认为有一种更好的方法来获得结果,但它虽然不完美,但仍然有效:

实际上,必须根据菜中的成分说明其成分: 首先是最新的,依此类推,虽然查询给出的成分列表包含以随机顺序排列的成分名称, 而它应遵循IngredientsID表中Products中所述的顺序: 因此

Flour,Fish,Water,Nuts

有没有办法做到这一点?

谢谢

0 个答案:

没有答案