Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite alias of table name in UPDATE statement

Tags:

alias

sqlite

I have a SQLite table called Price like this:

date,     productId, price
----------------------
20120601, 10       , 10.1
20120601, 20       , 20.1
20120602, 10       , 0
20120602, 20       , 0
20120602, 30       , 0

The table is created with this statement:

CREATE TABLE "Price" ("date" INTEGER NOT NULL , "productId" INTEGER NOT NULL , "price" DOUBLE, PRIMARY KEY ("date", "productId"))

I want to fill the price of date==20120602 with the price of the same product in the previous date.

i.e I want the table turn into like this:

date,     productId, price
----------------------
20120601, 10       , 10.1
20120601, 20       , 20.1
20120602, 10       , 10.1
20120602, 20       , 20.1
20120602, 30       , 0

So I tried this SQL statement:

UPDATE Price New SET New.price = 
    (SELECT old.price FROM Price Old WHERE New.date == 2 AND Old.date == 1 AND New.productId == Old.productId)

But SQLite gave me an error near dot.

Than I tried this statement:

UPDATE New Set New.Price = Old.Price
FROM Price New, Price Old
WHRER ......

SQLite gave me an error near FROM.

I double checked SQLite's SQL Syntax but found no lucky. Even I never tried so, I think both statements would work as expected in MS SQL Server. The first statement might work if New and Old are too different tables, but I need them in same table.

I really don't want to write a for loop to update once a line in my C++ code, I need advice on the right way to achieve this in SQLite.

Thank you.

like image 784
Zhao Xiang Avatar asked May 27 '12 08:05

Zhao Xiang


1 Answers

I myself have experienced this. Just remove word New after UPDATE Price and wherever you use New.something change to Price.something. I am sure there is a much nicer solution, but it works.

updated with code snippet from comments...

UPDATE Price 
SET
price = (SELECT old.price FROM Price Old WHERE Old.date = 1 AND price.productId = Old.productId) 
WHERE price.date = 2
like image 169
Andrius Naruševičius Avatar answered Oct 07 '22 10:10

Andrius Naruševičius