MySQL组重复ID而不丢失其他数据

时间:2017-11-23 01:14:52

标签: mysql database duplicates

我正在尝试制作一本食谱,但我遇到了重复问题。通过一个例子来理解它会更容易,所以让我们开始吧:

我的表格如下:

create table Recipe (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(25), 
    description VARCHAR(50), 
    instructions VARCHAR(500)) 
    ENGINE=InnoDB DEFAULT CHARSET=utf8;

create table Ingredient (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(50)) 
    ENGINE=InnoDB DEFAULT CHARSET=utf8; 

create table Measure (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(30)) 
    ENGINE=InnoDB DEFAULT CHARSET=utf8; 

create table RecipeIngredient (
    recipe_id INT NOT NULL, 
    ingredient_id INT NOT NULL, 
    measure_id INT, 
    amount INT, 
    CONSTRAINT fk_recipe FOREIGN KEY(recipe_id) REFERENCES Recipe(id), 
    CONSTRAINT fk_ingredient FOREIGN KEY(ingredient_id) REFERENCES Ingredient(id), 
    CONSTRAINT fk_measure FOREIGN KEY(measure_id) REFERENCES Measure(id)) 
    ENGINE=InnoDB DEFAULT CHARSET=utf8; 

当我运行如下所示的查询时:

SELECT r.name AS 'Recipe', 
    r.instructions, 
    ri.amount AS 'Amount', 
    mu.name AS 'Unit of Measure', 
    i.name AS 'Ingredient' 
FROM Recipe r 
JOIN RecipeIngredient ri on r.id = ri.recipe_id 
JOIN Ingredient i on i.id = ri.ingredient_id 
LEFT OUTER JOIN Measure mu on mu.id = measure_id;

我得到了这个结果:

enter image description here

问题在于,巧克力蛋糕是重复的,即使它是相同的食谱,它只有一种以上的成分。你能帮我解决这个问题,所以我会得到一个食谱实例吗?

1 个答案:

答案 0 :(得分:0)

使用GROUP_CONCAT将组中多行的值组合成逗号分隔列表。并使用CONCAT来连接字符串,例如将金额与单位和成分连接起来。

SELECT r.name, r.instructions,
    GROUP_CONCAT(CONCAT(ri.amount, mu.name, ' ', i.name)) AS ingredients
FROM Recipe r 
JOIN RecipeIngredient ri on r.id = ri.recipe_id 
JOIN Ingredient i on i.id = ri.ingredient_id 
LEFT OUTER JOIN Measure mu on mu.id = measure_id
GROUP BY r.id;