简体   繁体   中英

Given two SELECT statements, how to merge them to get one result minus the other?

I want to remove UNwantedIDs from wantedIDs , how to make sub-queries and get one result?

Here is my UNwantedIDs query:

SELECT 
    GROUP_CONCAT(DISTINCT `recipe_ingredient`.`recipeId` ORDER BY `recipe_ingredient`.`recipeId` ASC) UNwantedIDs
FROM `recipe_ingredient` 
WHERE `recipe_ingredient`.`ingredientId` 
     IN(SELECT `ingredient`.`ingredientId` AS unlinkIng 
        FROM `ingredient` 
        WHERE `ingredient`.`ingredientId` IN(1) or `ingredient`.`linkIngredientPerent` IN(1))
ORDER BY `recipeId` ASC  

http://sqlfiddle.com/#!2/84f00/5

Here is my wantedIDs query:

SELECT 
    GROUP_CONCAT(DISTINCT `recipe_ingredient`.`recipeId` ORDER BY `recipe_ingredient`.`recipeId` ASC) wantedIDs
FROM `recipe_ingredient` 
WHERE `recipe_ingredient`.`ingredientId` 
     IN(SELECT `ingredient`.`ingredientId` AS unlinkIng 
        FROM `ingredient` 
        WHERE `ingredient`.`ingredientId` IN(4,178) or    `ingredient`.`linkIngredientPerent` IN(4,178))
ORDER BY `recipeId` ASC  

http://sqlfiddle.com/#!2/84f00/4

Result ID like:

2,3,7,8,11,21,24,36,37,41,67,70,75,80,83,99,108 

I have this:

SELECT 
    GROUP_CONCAT(
        DISTINCT `recipe_ingredient`.`recipeId`
        ORDER BY `recipe_ingredient`.`recipeId` ASC
    ) wantedIDs
FROM `recipe_ingredient` 
WHERE `recipe_ingredient`.`ingredientId` 
     IN(SELECT `ingredient`.`ingredientId` AS unlinkIng 
        FROM `ingredient` 
        WHERE
          (`ingredient`.`ingredientId` IN(4,178) OR
           `ingredient`.`linkIngredientPerent` IN(4,178)
          )
      )
      AND `recipe_ingredient`.`recipeId` NOT IN (
          SELECT 
          `recipe_ingredient`.`recipeId`
             FROM `recipe_ingredient` 
          WHERE `recipe_ingredient`.`ingredientId` 
               IN (SELECT `ingredient`.`ingredientId` AS unlinkIng 
                  FROM `ingredient` 
                  WHERE `ingredient`.`ingredientId` IN(1) OR
                       `ingredient`.`linkIngredientPerent` IN(1)
               )
      )
ORDER BY `recipeId` ASC  

This is the result of a NOT IN used to merge the two queries. It is rather slow at the moment, probably because you need to add some indexes.

http://sqlfiddle.com/#!2/84f00/16

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM