比较两个表之间的列,并使用sql

时间:2017-11-01 02:47:51

标签: sql

我有两个表:table1和table2。我想将table1中的dx1与table2中的代码进行比较,如果它们匹配,我想创建一个名为' newversion'的新列。在dersiredoutout表中并用9.填充该特定行。我已经尝试了下面的代码,但它不起作用:(

表1

version   |    dx1
----------+----------
null      |   uuu98
null      |   asdf0
null      |   mnbv9

表2

code  |   description
------+---------------
asdf0 |   tadatada

期望的输出:

    version  |   dx1   | newversion
    ---------+---------+------------
    null     | uuu98   |
    null     | asdf0   |     9
    null     | mnbv9   |     

我的SQL:

CREATE OR REPLACE TEMP VIEW desiredoutput AS (
    SELECT * 
    FROM
        (SELECT 
             version, dx1, 
             CASE
                WHEN (SELECT dx1 
                      FROM table1 
                      WHERE (dx1 IN (SELECT code FROM table2)) AND version IS NULL)  
                   THEN 9
             END as newversion
         FROM 
             table1)
    )   

3 个答案:

答案 0 :(得分:2)

如果您只想在SELECT语句的输出中显示其他NewVersion列,那么

SELECT
    Table1.Version,
    Table1.Description,
    CASE WHEN Table2.code is NULL then NULL ELSE 9 END as NewVersion
FROM 
    Table1
    LEFT JOIN Table2 ON Table1.dx1 = Table2.code

应该适合你。

答案 1 :(得分:2)

您可以通过左连接执行此操作:

SELECT
    t1.version,
    t1.dx1,
    CASE WHEN t2.code IS NOT NULL THEN 9 END AS newversion
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.dx1 = t2.code

按照以下链接在MySQL中进行演示(您从未告诉我们您正在使用哪个数据库)。

Demo

答案 2 :(得分:1)

另一种方法是使用t2.codet1.dx1列与case进行比较,如下所示。

SELECT t1.version,
       t1.dx1,
       CASE
           WHEN t1.dx1 = t2.code THEN 9
       END AS newversion
FROM table1 t1
LEFT JOIN table2 t2 
ON t1.dx1 = t2.code;

<强> DEMO