MySQL UPDATE具有多个表和派生计算

时间:2014-02-25 15:07:07

标签: mysql join updates calculated-columns

我需要帮助MySQL UPDATE涉及两个表和一个计算值。最大的问题似乎是获得衍生价值。

我需要根据表2中的ID数量计算DENS列(按FIPS / Table.POP计算的总ID)

表1

---------------------
| FIPS | POP | DENS |
---------------------
| 0001 | 100 |      |
| 0002 |  25 |      |
| 0003 | 500 |      |
---------------------

表2

-------------
| ID | FIPS |
-------------
| 01 | 0001 |
| 02 | 0001 |
| 03 | 0002 |
| 04 | 0003 |
| 05 | 0003 |
| 06 | 0003 |
-------------

我无法弄清楚UPDATE语句的语法,以便将计数和后续计算与FIPS值正确关联。

我认为以下内容可能有效,但事实并非如此:

UPDATE Table1
SET Table1.DENS = (
   SELECT (COUNT(DISTINCT Table2.id) / Table1.POP )
   FROM Table2
   WHERE Table2.FIPS = Table1.FIPS
)

感谢任何帮助!

编辑:所需的结果如下:

----------------------
| FIPS | POP | DENS  |
----------------------
| 0001 | 100 | 0.020 |
| 0002 |  25 | 0.040 |
| 0003 | 500 | 0.006 |
----------------------

从表2和表1(使用POP:总ID / POP = DENS)计算DENS,因为FIPS 0001有2个ID(2/100 = 0.0200),FIPS 0002有1个ID(1/25) = 0.0400)和FIPS 0003的3个ID(3/500 = 0.0060)

3 个答案:

答案 0 :(得分:1)

尝试

UPDATE table1 t1
JOIN (
  SELECT FIPS, count( distinct ID ) As DENS
  FROM table2
  GROUP BY FIPS
) t2
ON t1.FIPS = t2.FIPS
SET t1.DENS = t2.DENS
;

答案 1 :(得分:1)

DROP TABLE IF EXISTS table1;

CREATE TABLE table1
(fips INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,pop INT NOT NULL
,dens DECIMAL(5,3) NULL
);

INSERT INTO table1 VALUES
(1,100,NULL),
(2,25,NULL),
(3,500,NULL);

DROP TABLE IF EXISTS table2;

CREATE TABLE table2
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,fips INT NOT NULL
);

INSERT INTO table2 VALUES
(1,1),
(2,1),
(3,2),
(4,3),
(5,3),
(6,3);


UPDATE table1 x
  JOIN 
     ( SELECT t1.fips,COUNT(t2.fips)/SUM(DISTINCT t1.pop) n FROM table1 t1 JOIN table2 t2 ON t2.fips = t1.fips GROUP BY t1.fips ) y
    ON y.fips = x.fips
   SET x.dens = n;

SELECT * FROM table1;
+------+-----+-------+
| fips | pop | dens  |
+------+-----+-------+
|    1 | 100 | 0.020 |
|    2 |  25 | 0.040 |
|    3 | 500 | 0.006 |
+------+-----+-------+

......或类似的东西

答案 2 :(得分:0)

正确的答案结果是两者的结合,增加了innodb_lock_wait_timeout的重置(设置为600)

SET SESSION innodb_lock_wait_timeout = 600

最终更新代码为:

UPDATE Table1 x
JOIN (SELECT t1.FIPS, COUNT(DISTINCT t2.ID)/t1.POP n
FROM Table1 t1
JOIN Table2 t2 ON t2.FIPS = t1.FIPS
GROUP BY t1.FIPS) y
ON y.fips = x.fips
SET x.DENS = n

感谢Kordirko和Strawberry的帮助!