views:

50

answers:

2

Hi:

I'd like to update values in one table based on corresponding values from other tables. Say you want to update prices of pieces provided by one specific manufacturer whose name is in the table Manufacturers with the Pieces table containing only the id of the manufacturer.

I've seen several solutions for MySQL here and for MS SQL Server here but none of them seems to work in SQLite.

Any suggestion?

+2  A: 

Have you tried something like this?

UPDATE Pieces
SET price = 42
WHERE manufacturer_id = (
    SELECT id
    FROM Manufacturers
    WHERE Name = 'FooBar Inc.'
)
Mark Byers
Yes, it works! Thanks. Shouldn't be `first(id)` in the nested SELECT?
Sergio
@OMG Ponies: Is SQLite, not MySQL. Why can't be two companies named `'FooBar Inc.'`? The uniqueness restriction applies only to the PK (id).
Sergio
@Sergio: Sorry about that, but point stands about potential duplicate data. The PK would be the ID, the name should have a unique constraint assuming supported by SQLite.
OMG Ponies
@Sergio: OMG Ponies has a good point. If there are two manufacturers with the same name, how would you know which to update? You probably don't want to update both. And just choosing the first one seems dangerous to me as you have a 50% chance of picking the wrong one. The query I gave you will fail if there are two companies with the same name, but I would say that's a reasonable thing to do in this situation.
Mark Byers
@OMG Ponies, @Mark: Fair enough!
Sergio
A: 

For SQLite there is no JOIN functionality in UPDATE statements. The only option you have is to make corellated subqueries:

UPDATE pieces 
    SET price = (SELECT SUM(price)
                 FROM manufacturers
                 WHERE pieces.manufacture_id = manufacturers.id)
WHERE manufacture_id in (SELECT id
                         FROM manufacturers
                         WHERE name IN ('boo', 'foo'));

That is not very efficient, but you can adjust it to your needs.

newtover