MySQL:插入...选择....重复键

时间:2016-09-20 09:45:48

标签: mysql

我有来自表A 的记录:

_____________________________________________________________________________
    Date       |      country        |      channel      |       clicks  
_____________________________________________________________________________
    1-01-2016  |         US          |        MTV        |        100

    1-01-2016  |         US          |        MTV        |         50
_____________________________________________________________________________

我将此记录插入另一个表B 使用查询:

INSERT INTO B 
SELECT 
  DATE,
  country,
  channel,
  SUM(clicks) AS clicks 
FROM
  A 
GROUP BY DATE,
  country,
  channel;

现在表B 看起来像:

_____________________________________________________________________________
    Date       |      country        |      channel      |       clicks  
_____________________________________________________________________________
    1-01-2016  |         US          |        MTV        |        150
_____________________________________________________________________________

在其他某个时刻,我在表A

中得到另一条记录
_____________________________________________________________________________
        Date       |      country        |      channel      |       clicks  
_____________________________________________________________________________
        1-01-2016  |         US          |        MTV        |        300
_____________________________________________________________________________

现在我想更新 表格B 中的旧记录,它应如下所示:

_____________________________________________________________________________
        Date       |      country        |      channel      |       clicks  
_______________________________________________________________________________
        1-01-2016  |         US          |        MTV        |        450
_____________________________________________________________________________

如何使用 MySQL

执行此操作

1 个答案:

答案 0 :(得分:2)

您可以使用相同的查询(用于insert)和INNER JOIN进行更新。

UPDATE B
INNER JOIN 
(
  SELECT 
    DATE,
    country,
    channel,
    SUM(clicks) AS clicks 
  FROM  A 
  GROUP BY DATE,  country,   channel
)AS t
ON B.Date = t.Date AND B.country = t.country AND B.channel = t.channel
SET B.clicks = t.clicks;

修改

为了update/insert通过相同的查询。

INSERT INTO B SELECT
    t.DATE,
    t.country,
    t.channel,
    t.clicks
FROM 
(
    SELECT
        DATE,
        country,
        channel,
        SUM(clicks) AS clicks
    FROM A
    GROUP BY DATE, country, channel 
) AS t
ON DUPLICATE KEY UPDATE clicks = t.clicks