如何通过将表a与表b的记录进行比较来创建新表?

时间:2019-07-18 12:23:46

标签: mysql sql database

我有两个表Table A和Table B比较每个字段并创建一个Table C,该表将数字转换为映射的颜色

表A包含:

n1 n2 n3 n4   
10 40 16 30    
30 40 16 10

表B包含:

Red Blue    
10   16   
40   30

每个@Strawberry建议的更新表B包含:

n_val color    
10   red   
40   red
16   blue
30   blue

我希望这样输出表C:

n1   n2  n3   n4    
Red  Red Blue Blue   
Blue Red Blue Red

我该如何在SQL中进行

3 个答案:

答案 0 :(得分:2)

这是一个奇怪的查询,但它提供了预期的结果

SELECT 
   CASE WHEN n1 IN (SELECT Red FROM tableB) THEN 'Red' ELSE 'Blue' END as n1,
   CASE WHEN n2 IN (SELECT Red FROM tableB) THEN 'Red' ELSE 'Blue' END as n2,
   CASE WHEN n3 IN (SELECT Red FROM tableB) THEN 'Red' ELSE 'Blue' END as n3,
   CASE WHEN n4 IN (SELECT Red FROM tableB) THEN 'Red' ELSE 'Blue' END as n4
FROM tableA

答案 1 :(得分:0)

归一化的设计可能看起来像这样:

table_A

id  n n_val
101 1 10  
102 1 30 

101 2 40 
102 2 40 

101 3 16 
102 3 16

101 4 30   
102 4 10

table_B

n_val colour
   10 red
   16 blue
   30 blue
   40 red 

答案 2 :(得分:0)

这是一个令人讨厌的查询,无法提供预期的结果;

select  (select colour from
            (
            select 'red' colour, red id from tableb
            union all 
            select 'blue',blue from tableb
            ) s where s.id = tablea.n1
            ) n1,
            (select colour from
            (
            select 'red' colour, red id from tableb
            union all 
            select 'blue',blue from tableb
            ) s where s.id = tablea.n2
            ) n2,
                        (select colour from
            (
            select 'red' colour, red id from tableb
            union all 
            select 'blue',blue from tableb
            ) s where s.id = tablea.n3
            ) n3,
                        (select colour from
            (
            select 'red' colour, red id from tableb
            union all 
            select 'blue',blue from tableb
            ) s where s.id = tablea.n4
            ) n4
from tablea;

+------+------+------+------+
| n1   | n2   | n3   | n4   |
+------+------+------+------+
| red  | red  | blue | blue |
| blue | red  | blue | red  |
+------+------+------+------+
2 rows in set (0.00 sec)