I have two tables, a "data" table with hundreds of thousands of rows, and a "settings" table with hundreds of rows. I need to update two values in the settings table, based on the sum of one column in the data table being greater than another column in the settings table, where the 'id' of the settings table matches the 'offerid' of the data table.
I've been cruising Google looking at many possible solutions, but I don't seem able to bend any of them to my needs. Any time I start working with Joins, I inevitably get tripped up.
My latest attempt which did not work, is:
UPDATE settings a, data b
SET a.hidden=1, a.weight=0
WHERE a.id = b.offerid
AND sum(b.views) > a.target
I liked this flavor of approach as I thought it actually made sense to me, but all I get is "Error code 1111: Invalid us of group function"
. Maybe someone here can point me in the right direction.
It errors out because you are using an aggregate function (sum) with no grouping. So query really does not know which rows should be summed together. You can use a subquery like this:
UPDATE settings a
INNER JOIN
(
SELECT
sum(b.views) sumviews, b.offerid
from data b
group by b.offerid
) c on c.offerid = a.id
SET a.hidden=1, a.weight=0
where c.sumviews>a.target
EDIT: To disable the safe update function do the following steps
Follow the steps below before executing the UPDATE command:
Go to Edit --> Preferences Click "SQL Queries" tab and uncheck "Safe Updates" check box Query --> Reconnect to Server Now execute your sql query
Source: Disable Safe Update
Try using
HAVING
instead of
AND
So your code goes like:
UPDATE settings a, data b
SET a.hidden=1, a.weight=0
WHERE a.id = b.offerid
GROUP BY a.id
HAVING sum(b.views) > a.target
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.