MySQL查询根据另一列查找匹配列?

时间:2016-11-13 20:48:31

标签: mysql

抱歉,我不知道如何说出问题的标题。 我有这样一张桌子

Prod       Part      Number

0001       101       3
0001       102       2
0001       103       1

0002       101       3
0002       102       2
0002       103       4

0003       101       2
0003       102       3
0003       103       6

0004       101       3
0004       102       2
0004       103       1

我想找到所有部件的每个部件的编号正确的产品。 像

这样的东西
SELECT Prod from table 
WHERE     (Number of Part(101)) = 3 
      AND (Number of Part(102)) = 2 
      AND (Number of Part(103)) = 1

输出将是:

Prod
0001
0004

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以使用一些内连接

  select t1.Prod from 
  ( select Prod 
  from my_table 
  where part = 101
  and Number = 3 )  t1
  inner join  
  ( select Prod 
  from my_table 
  where part = 102
  and Number = 2 )  t2 on t1.Prod = t2.Prod
  inner  join 
  ( select Prod 
  from my_table 
  where part = 103
  and Number = 1 ) t3 on t1.Prod = t3.Prod

http://sqlfiddle.com/#!9/014fe4/8

答案 1 :(得分:0)

通过条件聚合:

SELECT Prod, 
       SUM(CASE WHEN Part = 101 AND Number = 3 OR
                     Part = 102 AND Number = 2 OR
                     Part = 103 AND Number = 1 
           THEN 1 ELSE 0 END) sum
FROM tbl 
GROUP BY Prod
HAVING sum = 3  

这将为您提供额外的列。如果这是一个问题,那么将所有内容包装到另一个SELECT中。