MySQL将两个SELECT查询组合成一个检查重复值

时间:2014-05-19 16:00:57

标签: php mysql sql

鉴于这两个简单的查询:

SELECT materialID FROM materials WHERE compoundNumber = "<some user input1>";
SELECT materialID FROM materials WHERE vendorCompoundNumber = "<some user input2>";

如何将它们组合成一个查询,结果集如下所示:

materialID | compoundDupFound | vendorCompoundDupFound

1          |                0 |                      1

              - - or - -

2          |                1 |                      0 

              - - or - -

3          |                1 |                      1

我意识到我可以执行另一个但是我想知道是否有一个聪明的内置方法来构建查询以同时执行这两个操作。

列compoundnumber&amp; vendorCompoundNumber需要在数据库中是唯一的,因此我检查表单并确保用户输入一些独特的内容。我将根据结果集显示错误消息。

2 个答案:

答案 0 :(得分:2)

可以使用OR运算符组合查询

SELECT materialID, compoundNumber AS compoundDupFound, vendorCompoundNumber AS vendorCompoundDupFound
FROM materials 
WHERE compoundNumber = "input1"
   OR vendorCompoundNumber = "input2";

根据评论,看起来你需要知道哪些是匹配的。所以这回到UNION陈述,但是从另一个回答谈​​论这条路径的一小部分改变

SELECT materialID, compoundNumber AS compoundDupFound, NULL as vendorCompoundDupFound
    FROM materials 
    WHERE compoundNumber = "input1"
UNION
SELECT materialID, NULL, vendorCompoundNumber AS vendorCompoundDupFound
    FROM materials 
    WHERE vendorCompoundNumber = "input2"

这应该让你的输出尽可能接近原始问题。通过这种方式,您将获得匹配的记录或NULL,然后可以判断匹配的记录。

答案 1 :(得分:1)

也可以使用UNION。如果您不想检查重复项 - 您需要使用UNION ALL。

SELECT materialID FROM materials WHERE compoundNumber = "<some user input1>"
UNION 
SELECT materialID FROM materials WHERE vendorCompoundNumber = "<some user input2>"