SQL - 如何在与另一个表进行比较后返回多个值并再次比较返回值?

时间:2014-08-08 07:02:12

标签: mysql sql sql-server

需要上述查询的帮助。基本上我有表A和B。

表A

+-------------+
|Paper| Stone
+-------------+
| A1  | B1 |
| A2  | B2 |
| A3  | B3 |
+-------------+

表B

+-------------+
|Paper| Stone
+-------------+
|A1   | B1
|A1   | B3
|A1   | B1
|A2   | B2
+-------------+

首先,我需要获得表A纸并与表B纸匹配,以将匹配的石头值返回到表C中,

但是有条件,因为例如A1有很多Stone值。

首先,表B的石头值与表A的石头值匹配仅返回

其次,如果石头值不匹配,那么它就是空白。

样本表C如下所示。

Table C
+--------------------+
|Paper| Stone | Match
+--------------------+
|A1   |  B1 |  B1
|A2   |  B2 |  B2
|A3   |  B3 |
+--------------------+

1 个答案:

答案 0 :(得分:0)

考虑这个例子......

 DROP TABLE IF EXISTS table_a;

 CREATE TABLE Table_A
 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
 ,paper CHAR(2) NOT NULL
 ,stone CHAR(2) NOT NULL
 );

 INSERT INTO table_a (paper,stone) VALUES
 ('A1','B1'),
 ('A2','B2'),
 ('A3','B3');

 DROP TABLE IF EXISTS table_b;

 CREATE TABLE Table_B
 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
 ,paper CHAR(2) NOT NULL
 ,stone CHAR(2) NOT NULL
 );

 INSERT INTO table_b (paper,stone) VALUES
 ('A1','B1'),
 ('A1','B3'),
 ('A1','B1'),
 ('A2','B2');

 SELECT DISTINCT a.*
               , b.stone
            FROM table_a a
            LEFT
            JOIN table_b b
              ON b.paper = a.paper 
             AND b.stone = a.stone;

 +----+-------+-------+-------+
 | id | paper | stone | stone |
 +----+-------+-------+-------+
 |  1 | A1    | B1    | B1    |
 |  2 | A2    | B2    | B2    |
 |  3 | A3    | B3    | NULL  |
 +----+-------+-------+-------+