我如何只选择我有配料的食谱?

时间:2016-04-27 08:38:03

标签: php sql mariadb

我正在执行以下声明:

SELECT DISTINCT
  r.Recipe_Name
FROM
  USER u
INNER JOIN
  UserIngredient ui
ON
  u.User_ID = ui.User_ID
INNER JOIN
  RecipeIngredient ri
ON
  ui.Ingredient_ID = ri.Ingredient_ID
INNER JOIN
  Ingredient i
ON
  ri.Ingredient_ID = i.Ingredient_ID
INNER JOIN
  Recipe r
ON
  ri.Recipe_ID = r.Recipe_ID
WHERE
  u.User_Session = SessionID

并获得每种配方,我至少有一种成分,而不仅仅是我有所有成分的配方。我的表格布局如下:

CREATE TABLE User
(
    User_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    User_Pass TEXT NOT NULL,
    User_Name TEXT NOT NULL,
    User_Surname TEXT NOT NULL,
    User_EMail VARCHAR(255) UNIQUE,
    User_Session VARCHAR(50) UNIQUE,
    User_Admin BOOLEAN,
    User_Newsletter BOOLEAN
);
CREATE TABLE Recipe
(
    Recipe_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    Recipe_Name VARCHAR(255) UNIQUE NOT NULL,
    Recipe_Clicks INT,
    Recipe_Description TEXT,
    Recipe_Image VARCHAR(255) DEFAULT 'https://placehold.it/400x500'
);
CREATE TABLE Ingredient
(
    Ingredient_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    Ingredient_Name VARCHAR(255) UNIQUE,
    Ingredient_Description TEXT
);
CREATE TABLE RecipeIngredient
(
    RecipeIngredient_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    RecipeIngredient_Amount DECIMAL(8,2) NOT NULL,
    MeasuringUnit_ID INT NOT NULL,
    Recipe_ID INT NOT NULL,
    Ingredient_ID INT NOT NULL,
    FOREIGN KEY (MeasuringUnit_ID) REFERENCES MeasuringUnit(MeasuringUnit_ID),
    FOREIGN KEY (Recipe_ID) REFERENCES Recipe(Recipe_ID),
    FOREIGN KEY (Ingredient_ID) REFERENCES Ingredient(Ingredient_ID)
);
CREATE TABLE UserIngredient
(
    UserIngredient_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    Ingredient_ID INT NOT NULL,
    User_ID INT NOT NULL,
    FOREIGN KEY(Ingredient_ID) REFERENCES Ingredient(Ingredient_ID),
    FOREIGN KEY(User_ID) REFERENCES User(User_ID)
);

我得到的结果:

我得到每种配方都有一种成分

我想要的结果:

我有所有成分的所有食谱。

Here是我的SQL文件

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT DISTINCT r.Recipe_Name
FROM Recipe r
CROSS JOIN User u
WHERE
    (SELECT COUNT(*) 
     FROM RecipeIngredients ri
     LEFT OUTER JOIN UserIngredient ui
     ON ri.Recipe_ID = ui.Recipe_ID
     AND ri.Ingredient_ID = ui.Ingredient_ID
     AND ui.User_ID = u.User_ID
     WHERE ui.UserIngredient_ID IS NULL) = 0