简体   繁体   English

根据另一个表中一列的总和在一个表中设置两个值

[英]Set two values in one table based on sum of a column in another table

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. 我需要根据数据表中一列的总和大于设置表中另一列的总和来更新设置表中的两个值,其中设置表的“ id”与数据表的“ offerid”匹配。

I've been cruising Google looking at many possible solutions, but I don't seem able to bend any of them to my needs. 我一直在游说Google寻找许多可能的解决方案,但我似乎无法满足我的需求。 Any time I start working with Joins, I inevitably get tripped up. 每当我开始使用Joins时,都会不可避免地被绊倒。

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" . 我喜欢这种方式,因为我认为这实际上对我有意义,但我得到的只是"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: 在执行UPDATE命令之前,请按照以下步骤操作:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM