Update row with select on same table

后端 未结 5 509
醉话见心
醉话见心 2021-01-11 12:13

I\'m trying to update row with same table query. Context:

ID        |  LANG       |  TEXT
----------------------------------
1         |  EN         |  Hello         


        
相关标签:
5条回答
  • 2021-01-11 12:19
    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
    
    0 讨论(0)
  • 2021-01-11 12:27

    You don't specify the database. The following is standard 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;
    

    In the event of duplicates, the following should work:

    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;
    

    EDIT:

    Of course, not all databases support all ANSI standard functionality. In MySQL, you would use a join instead:

    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;
    
    0 讨论(0)
  • 2021-01-11 12:29
    UPDATE TABLE
        SET
            TEXT = (SELECT TOP 1 text WHERE id = table.id AND LANG ='EN' AND TEXT IS NOT NULL) 
    WHERE
        TEXT IS NULL;
    
    0 讨论(0)
  • 2021-01-11 12:35

    For MS SQL you can use a join to do this, it might not work with other databases though:

    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

    0 讨论(0)
  • 2021-01-11 12:36
    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
    
    0 讨论(0)
提交回复
热议问题