在同一个表上选择更新行

时间:2014-08-12 14:26:48

标签: sql sql-update

我尝试使用相同的表查询更新行。上下文:

ID        |  LANG       |  TEXT
----------------------------------
1         |  EN         |  Hello
1         |  FR         |
1         |  ES         |
2         |  EN         |  Boat
2         |  FR         |  Bateau
2         |  ES         |

我想: 对于每一行;如果 TEXT为空;使用具有相同ID和LANG =' EN'。

的行的TEXT值更新它

执行类似操作的SQL请求是什么?

5 个答案:

答案 0 :(得分:9)

您没有指定数据库。以下是标准SQL:

UPDATE t
    SET TEXT = (SELECT text
                FROM t t2
                WHERE t.id = t2.id AND LANG ='EN' AND
                      TEXT IS NOT NULL
               ) 
    WHERE TEXT IS NULL;

如果出现重复,以下情况应该有效:

UPDATE t
    SET TEXT = (SELECT max(text)
                FROM t t2
                WHERE t.id = t2.id AND LANG ='EN' AND
                      TEXT IS NOT NULL
               ) 
    WHERE TEXT IS NULL;

编辑:

当然,并非所有数据库都支持所有ANSI标准功能。在MySQL中,您将改为使用join

UPDATE t JOIN
       (SELECT id, max(text) as text_en
        FROM t t2
        WHERE LANG ='EN' AND TEXT IS NOT NULL
       ) ten 
       ON t.id = ten.id
    SET t.TEXT = ten.text_en
    WHERE t.TEXT IS NULL;

答案 1 :(得分:4)

对于MS SQL,您可以使用连接来执行此操作,但它可能不适用于其他数据库:

UPDATE t1
SET t1.text = t2.text
FROM table1 t1
INNER JOIN table1 t2 ON t1.id = t2.id 
WHERE t1.TEXT IS NULL AND t2.LANG = 'EN'

Sample SQL Fiddle

答案 2 :(得分:1)

UPDATE TABLE
SET TEXT = (SELECT TOP 1 text WHERE id = table.id AND LANG ='EN' AND TEXT IS NOT NULL) --TOP 1 INCASE YOU HAVE DUPLICATES
WHERE TEXT IS NULL

答案 3 :(得分:0)

Update Test T1  INNER JOIN (SELECT T2.ID AS "id",MAX(T2.TEXTV) AS "MTEXT" FROM TEST T2
                             WHERE T2.LANG = 'EN'
                             AND T2.TEXTV IS NOT NULL   
                             GROUP BY T2.ID ) AS DER          
            ON T1.ID = DER.id

SET T1.TEXTV = DER.MTEXT
WHERE T1.TEXTV IS NULL ;   ------MySQL Query

答案 4 :(得分:0)

UPDATE TABLE
    SET
        TEXT = (SELECT TOP 1 text WHERE id = table.id AND LANG ='EN' AND TEXT IS NOT NULL) 
WHERE
    TEXT IS NULL;