Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update row with select on same table

Tags:

sql

sql-update

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

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

I want to : For each row; if TEXT IS NULL; update it with TEXT value of row with same ID and LANG = 'EN'.

What is the SQL request to do something like that ?

like image 611
bux Avatar asked Aug 12 '14 14:08

bux


People also ask

How do I use UPDATE and SELECT together in SQL?

The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.

Can we use SELECT and UPDATE together?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.

How do you UPDATE a row in a list in a table?

Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- WHERE condition; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data.

How can we UPDATE one column value with another column in the same table?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.


1 Answers

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;
like image 188
Gordon Linoff Avatar answered Oct 21 '22 11:10

Gordon Linoff