I want to update one table with the help of the foreign key of others table.
I am trying to do something like this:
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT tbl_2.item1
FROM tbl_1, tbl_2
WHERE tbl_1.field3 = tbl_2.item1 AND tbl_2.item2 = 135)
OR
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT item1 FROM tbl_2 WHERE item2 = 135)
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.
SQLite UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be updated.
Open the database that contains the records you want to update. On the Create tab, in the Queries group, click Query Design. Click the Tables tab. Select the table or tables that contain the records that you want to update, click Add, and then click Close.
I think either of the following will work:
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE EXISTS
( SELECT 1
FROM tbl_2
WHERE tbl_1.field3 = tbl_2.item1
AND tbl_2.item2 = 135
)
OR
UPDATE tbl_1
SET field1 = 6, field12 = NULL
WHERE field3 IN (SELECT item1 FROM tbl_2 WHERE item2 = 135)
This is because the SELECT returns more than one row. Do this instead:
UPDATE tbl_1 SET field1 = 6, field12 = NULL
WHERE field3 IN (SELECT item1 FROM tbl_2 WHERE item2 = 135)
When SELECT
returns a table (or multiple rows) IN
is used. If you are sure the inner query should return only one row, then you will have to adjust the inner query accordingly. Like this or so:
UPDATE tbl_1 SET field1 = 6, field12 = NULL
WHERE field3 = (SELECT item1 FROM tbl_2 WHERE item2 = 135 ORDER BY myValue LIMIT 1)
Its safer to use IN
here 'cos it can handle both single record and multiple records returned from the SELECT statement.
You can also use an INSERT OR REPLACE statement, something like the following:
Assume tbl_1 has 4 columns: key, field1, field2, field3
and you want to update field2 with the matching value from tbl_2
INSERT OR REPLACE INTO tbl_1
SELECT tbl_1.key, tbl_1.field1, tbl_2.value, tbl_1.field3
FROM tbl_1 JOIN tbl_2 ON tbl_2.key = tbl_1.key
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With