I have been trying to update some values in a sqlite3 table but I am having loads of problems with the `sqlite3.OperationalError: near “GROUP”: syntax error. I have been following the documentation but I am not been very successful to correct the error. What I am trying to do is to find the all_numbers with a value =0 and updated with the max(value)+1 I just need to say that I am new creating databases so any help would be highly appreciated. Thanks in advance.
JavaScript
x
23
23
1
> def update_tables(connection): #function to update table
2
> c = connection.cursor() # i have a separated def to create the connection
3
> data = """SELECT id, cps, all_numb FROM all_records""" #this is my column selection
4
> c.execute(data)
5
> rows = (c.fetchall())
6
> # print(rows)
7
> _list = []
8
> for row in rows: # I try to use a python loop to iterate through the rows
9
> id = row[0]
10
> cps = row[1]
11
> all_numb = row[2]
12
> if cps not in _list:
13
> _list.append(cps)
14
> if cps in _list: #here I tried a for loop but it does not work
15
> sq3 = """UPDATE all_records # this is the update selection
16
> SET all_numb =(SELECT MAX(all_numb) +1)
17
> WHERE cps =cps AND all_numb = 0
18
19
> GROUP BY cps"""
20
> c.execute(sq3)
21
> connection.commit()
22
> c.fetchall()
23
Advertisement
Answer
I think this is what you’re trying to do:
JavaScript
1
9
1
UPDATE all_records AS r1
2
SET all_numb = last_numb + 1
3
FROM (
4
SELECT r2.cps, MAX(r2.all_numb) AS last_numb
5
FROM all_records AS r2
6
GROUP BY r2.cps
7
)
8
WHERE r1.cps = r2.cps AND all_numb = 0
9
See the documentation of UPDATE FROM
I’m not sure why you’re doing this in a for
loop, since you’re not using any of the variables in the loop. This updates the entire table at once, so it doesn’t need to be in a loop.