duanpo7282 2014-05-19 16:00
浏览 88
已采纳

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

Given these two simple queries:

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

How can I make them into one query with the result set look something like this:

materialID | compoundDupFound | vendorCompoundDupFound

1          |                0 |                      1

              - - or - -

2          |                1 |                      0 

              - - or - -

3          |                1 |                      1

I realize I can perform one then the other but I'm wondering if there is a clever built in way to construct a query to do both at once.

The columns compoundNumber & vendorCompoundNumber need to be unique in the database so I'm checking a form and making sure the user inputs something unique. I will display an error message based on the result set.

  • 写回答

2条回答 默认 最新

  • duanli8391 2014-05-19 16:01
    关注

    Can use the OR operator to combine queries

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

    Based on the comments, it looks like you need to know which was matched as well. So this points back to a UNION statement, but with a small change from the other answer talking about this path

    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"
    

    That should give you output as close as possible to the original question. This way you will get matched records or NULL, and then can tell which was matched.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换