比较同一个表中的两列,并使用结果更新新列

时间:2013-11-18 10:36:08

标签: sql ms-access ms-access-2007

我有一个名为table1的表 它有两个名为“name1”和“name2”的字段 我想将这两列相互比较 如果name1有一个name2中不存在的值,我想知道填写一个新的标志列,反之亦然

table1 : 
----
name1  name2
----
jack   wheile
--
james  jack
--

>        
sample output : 
--
name1  name2   flag
--
jack   wheile  jack exist in column2
--
james  jack    jack exist in column1
--

任何帮助?

2 个答案:

答案 0 :(得分:0)

尝试此查询:

UPDATE TABLE1 SET FLAG = CONCAT('exist in ', IF(NAME1 LIKE '%jack%', column1, column2)) 
WHERE NAME1 LIKE '%jack%' OR NAME2 LIKE '%jack%';

答案 1 :(得分:0)

如果从Access本身

中执行,此查询应该达到所需的结果
UPDATE table1 SET
    flag = Switch(DCount("*", "table1", "[name2]=""" & Replace([name1], """", """""") & """")>0, [name1] & " exists in column 2", DCount("*", "table1", "[name1]=""" & Replace([name2], """", """""") & """")>0, [name2] & " exists in column 1")

编辑:

或者,以下方法可以证明效率更高,但需要两次UPDATE查询

UPDATE table1 SET flag = [name1] & " exists in column 2"
WHERE 
    [name1] IN
        (
            SELECT x.name1 
            FROM 
                table1 AS x 
                INNER JOIN 
                table1 AS y 
                    ON x.name1 = y.name2
        )

UPDATE table1 SET flag = [name2] & " exists in column 1"
WHERE 
    [name2] IN
        (
            SELECT y.name2 
            FROM 
                table1 AS x 
                INNER JOIN 
                table1 AS y 
                    ON x.name1 = y.name2
        )