SQL多表查询

时间:2017-11-21 19:34:24

标签: mysql sql

我有三个关系:食谱(名称,描述),成分(recipeName,num,val)和步骤(recipeName,num,val)。每个配方将具有一种或多种成分,以及一个或多个步骤。我正在尝试编写一个查询,列出单个配方的成分和步骤。有了这个查询

SELECT Recipes.name, Recipes.descr, Ingredients.num, Ingredients.val, Steps.num, Steps.val
FROM Recipes 
LEFT OUTER JOIN Ingredients ON Recipes.id = Ingredients.recipeName  
LEFT OUTER JOIN Steps ON Recipes.id = Steps.recipeName;

此查询就像一个交叉产品。因此,如果某些食谱的成分值为1,则ing-a和2,ing-b和步骤值为1,step-c,2,step-d和3,step-e,我得到(order is Recipe.name ,recipe.descr,Ingredients.num,Ingredients.val,Steps.num,Steps.val)

name, descr, 1, ing-a, 1, step-c
name, descr, 1, ing-a, 2, step-d
name, descr, 1, ing-a, 3, step-e
name, descr, 2, ing-b, 1, step-c
name, descr, 2, ing-b, 2, step-d
name, descr, 2, ing-b, 3, step-e

是否存在如下所示返回的查询(配方值,然后是成分,然后是步骤)

name
descr
1,ing-a
2,ing-b
1,step-c
2,step-d
3,step-e

2 个答案:

答案 0 :(得分:1)

数据

DROP TABLE iF EXISTS Recipes;
DROP TABLE iF EXISTS Ingredients;
DROP TABLE iF EXISTS Steps;

CREATE TABLE Recipes
(id INT,
 name VARCHAR(100),
 descr VARCHAR(100));

CREATE TABLE Ingredients
(recipeName INT,
 num INT,
 val VARCHAR(100));

CREATE TABLE Steps
(recipeName INT,
 num INT,
 val VARCHAR(100)); 

INSERT INTO  Recipes VALUES (1, 'name', 'descr');

INSERT INTO Ingredients VALUES (1, 1, 'ing-a');
INSERT INTO Ingredients VALUES (1, 2, 'ing-b');
INSERT INTO Ingredients VALUES (1, 3, 'ing-c');

INSERT INTO Steps VALUES (1, 1, 'step-a');
INSERT INTO Steps VALUES (1, 2, 'step-b');
INSERT INTO Steps VALUES (1, 3, 'step-c');

<强>解决方案

SELECT v1.display
  FROM (    SELECT Recipes.id AS sort_key, 1 AS seq, Recipes.name AS display
              FROM Recipes
            UNION ALL
            SELECT Recipes.id AS sort_key, 2 AS seq, Recipes.descr AS display
              FROM Recipes
            UNION ALL
            SELECT Ingredients.recipeName AS sort_key, 3 AS seq, CONCAT(Ingredients.num , ',' , Ingredients.val) AS display
              FROM Ingredients 
            UNION ALL
            SELECT Steps.recipeName AS sort_key, 4 AS seq, CONCAT(Steps.num , ',' , Steps.val) AS display
              FROM Steps ) v1
 ORDER BY v1.sort_key, v1.seq, v1.display; 

<强>输出

***display***
name
descr
1,ing-a
2,ing-b
3,ing-c
1,step-a
2,step-b
3,step-c

答案 1 :(得分:0)

我刚看到问题已更改以下内容可能无效。

您可以使用group concat执行此操作,如下所示:

SELECT
  Recipes.name, Recipes.descr,
  GROUP_CONCAT(CONCAT(Ingredients.num,' ',Ingredients.val) SEPARATOR ', ') AS Ingredients,
  GROUP_CONCAT(CONCAT(Steps.num,' ',Steps.val) SEPARATOR ', ') AS Steps
FROM Recipes 
LEFT OUTER JOIN Ingredients ON Recipes.id = Ingredients.recipeName  
LEFT OUTER JOIN Steps ON Recipes.id = Steps.recipeName;
GROUP BY Recipes.name, Recipes.descr