在mysql中的条件下使用join更新记录

时间:2018-08-16 10:54:16

标签: mysql

我有2张桌子

utr_details

utr | utr_amt |match_flag(default 0)
1   |10       |0
1   |20       |0
1   |20       |0
2   |30       |0
2   |20       |0
2   |10       |0

export_data
utr | utr_sum_amt
1   | 50
2   | 100

如上所示,表utr 1的utr_details中utr_amt的总和为50,这等于对utr 1的export export_data中的utr_sum_amt。 但是两个表中的utr 2的总和都不相等。 我的任务是将match_flag的值更新为1,其中两个表的总和相等。在这种情况下,表utr_details中的utr 1的match_flag将为1。 请帮我生成一个mysql查询。是否可以在单个查询中实现?

3 个答案:

答案 0 :(得分:1)

也许这里的查询比严格必要的要多,但是您明白了...

DROP TABLE IF EXISTS utr_details;

CREATE TABLE utr_details
(id SERIAL PRIMARY KEY
,utr INT NOT NULL
,utr_amt INT NOT NULL
,match_flag TINYINT NOT NULL DEFAULT 0
);

INSERT INTO utr_details VALUES
(1,1,10,0),
(2,1,20,0),
(3,1,20,0),
(4,2,30,0),
(5,2,20,0),
(6,2,10,0);

DROP TABLE IF EXISTS export_data;

CREATE TABLE export_data
(utr INT NOT NULL PRIMARY KEY
,utr_sum_amt INT NOT NULL
);

INSERT INTO export_data VALUES
(1, 50),
(2,100);

UPDATE utr_details a 
  JOIN 
     ( SELECT x.utr 
         FROM 
            ( SELECT utr
                   , SUM(utr_amt) utr_sum_amt 
                FROM utr_details 
               GROUP 
                  BY utr
            ) x 
         JOIN export_data y 
           ON y.utr = x.utr 
          AND y.utr_sum_amt = x.utr_sum_amt
     ) b 
    ON b.utr = a.utr 
   SET match_flag = 1;
Query OK, 3 rows affected (0.05 sec)

SELECT * FROM utr_details;
+----+-----+---------+------------+
| id | utr | utr_amt | match_flag |
+----+-----+---------+------------+
|  1 |   1 |      10 |          1 |
|  2 |   1 |      20 |          1 |
|  3 |   1 |      20 |          1 |
|  4 |   2 |      30 |          0 |
|  5 |   2 |      20 |          0 |
|  6 |   2 |      10 |          0 |
+----+-----+---------+------------+

答案 1 :(得分:0)

查询看起来像这样:

UPDATE utr_details 
SET match_flag = 1
WHERE utr IN (
SELECT utr, utr_sum_amt, auto_sum.sum.correct
FROM export_data 
INNER JOIN 
(SELECT utr, SUM(utr_amt) AS sum_correct
FROM utr_details
GROUP BY utr) auto_sum
WHERE utr_sum_amt = auto_sum.sum.correct
)

这是它的工作方式。

1)计算实际总和:

SELECT utr, SUM(utr_amt) AS sum_correct
FROM utr_details
GROUP BY utr

2)将export_data与这个新选择一起加入,并添加一个WHERE子句以仅选择总和不同的行。

3)使用以上结果作为过滤器运行UPDATE

答案 2 :(得分:0)

UPDATE utr_details 
   JOIN (SELECT aggregates.utr 
         FROM   (SELECT utr, Sum(utr_amt) utr_total 
                 FROM   utr_details 
                 GROUP  BY utr) aggregates 
                JOIN export_data 
                  ON aggregates.utr = export_data.utr 
         WHERE  utr_total = utr_sum_amt) aggregates_equal 
     ON aggregates_equal.utr = utr_details.utr 
SET match_flag = 1;