需要两个选择查询帮助

时间:2012-05-09 06:00:08

标签: php mysql database

SELECT r.nid 
FROM recipe_node_ingredient r,recipe_ingredient ri 
WHERE r.`ingredient_id` = ri.id 
AND ri.name = 'carrot' 
AND r.nid NOT IN (SELECT r.nid 
                  FROM recipe_node_ingredient r,recipe_ingredient ri
                  WHERE  r.`ingredient_id` = ri.id AND ri.name = 'salt');

此查询将返回节点ID ..

此查询还返回节点ID。

 SELECT nid 
 FROM  taxonomy_index JOIN taxonomy_term_data USING (tid) 
 WHERE name IN ('Desert."', 'Indian')
 GROUP BY nid HAVING COUNT(*) > 1

是否可以在MySQL查询中检查两个返回节点id是否相等..?

4 个答案:

答案 0 :(得分:1)

MYSQL中没有任何内容可以检查查询中的内容是否相等(结果是从不同的查询返回的) 您的要求是业务逻辑。因此,您获取第一个查询的返回值并返回第二个查询的值,并在代码中进行比较!

答案 1 :(得分:1)

嗯,你可以尝试这样的事情:

SELECT *
FROM (SELECT r.nid
      FROM recipe_node_ingredient r,
           recipe_ingredient ri
      WHERE r.`ingredient_id` = ri.id
      AND   ri.name = 'carrot'
      AND   r.nid NOT IN (SELECT r.nid
                          FROM recipe_node_ingredient r,
                               recipe_ingredient ri
                          WHERE r.`ingredient_id` = ri.id
                          AND   ri.name = 'salt')) subSelect1,
     (SELECT nid
      FROM taxonomy_index 
        JOIN taxonomy_term_data USING (tid)
      WHERE name IN ('Desert."','Indian')
      GROUP BY nid
      HAVING COUNT(*) > 1) subSelect2
WHERE subSelect1.nid = subSelect2.nid

如果您没有从此查询中获得结果,则nids不匹配。

答案 2 :(得分:1)

如何使用FULL OUTER JOIN比较结果?

SELECT
  nid, 
  IFNULL(from_recipe, 0) from_recipe, 
  IFNULL(from_taxonomy, 0) from_taxonomy
FROM
  (
    SELECT   r.nid, 1 AS from_recipe
    FROM     recipe_node_ingredient r
    WHERE    EXISTS (
               SELECT 1 FROM recipe_ingredient WHERE id = r.ingredient_id AND name = 'carrot'
             )
             AND NOT EXISTS (
               SELECT 1 FROM recipe_ingredient WHERE id = r.ingredient_id AND name = 'salt'
             )
  ) AS recipe
  FULL OUTER JOIN (
    SELECT   ti.nid, 1 AS from_taxonomy
    FROM     taxonomy_index td
             INNER JOIN taxonomy_term_data ti ON td.tid = it.tid
    WHERE    td.name IN ('Desert."', 'Indian')
    GROUP BY ti.nid 
    HAVING   COUNT(*) > 1
  ) AS taxonomy ON recipe.nid = taxonomy.nid
WHERE
  IFNULL(from_recipe, 0) + IFNULL(from_taxonomy, 0) = 1

WHERE from_recipe + from_taxonomy = 1将返回仅在一个查询中的行。使用= 2查看另一半或完全离开以查看哪一个。

答案 3 :(得分:0)

select if(select r.nid from recipe_node_ingredient r,recipe_ingredient ri where
r.`ingredient_id` = ri.id and ri.name = 'carrot' and r.nid 
NOT IN (select r.nid from recipe_node_ingredient r,recipe_ingredient ri
where  r.`ingredient_id` = ri.id and ri.name = 'salt') == (SELECT nid FROM  taxonomy_index JOIN taxonomy_term_data
 USING (tid) WHERE name IN ('Desert."', 'Indian')
 GROUP BY nid HAVING COUNT(*) > 1),'true','false')