SQL sqlite conditional query in sqlite (for Android)
Hello I have a table with that structure:
ID VALUE
1 3
2 5
3 12
if I query select id,value,value+5 from table. Thats the result
ID VALUE NEW_VALUE
1 3 8
2 5 10
3 12 17
And what I want to make a query indicating the id and the new value that return the whole table but with a 3rd column indicating the new values after inserting. for example for myQuery(id=2,value=8)
ID VALUE NEW_VALUE
1 3 3
2 5 8
3 12 12
Is posib开发者_StackOverflow中文版le to do that in the same query?
YOu can use the WHERE clause to select only the rows you want ("...if the student has the given id..."
):
update T
set col3 = col2 + 5
where id = 2
Of course, col3 would have to exist before you can update it. So you will either have to issue an ALTER-TABLE statement (if your implementation supports it) or recreate the table with the desired columns, import the original data (INSERT INTO YOURNEWTABLE...SELECT ... from YOUROLDTABLE) and then update col3.
If you don't want to "persist" this third column but only need it to be displayed when you query:
select id, col2, col2 + 5 as myComputedValue
from T
where id = 2
Finally, if you want to display all rows but change the addend conditionally (add zero to col2 when the id is not one of the ones you desire but add 5 when it is) then you can use the CASE statement.
精彩评论