使用MySQL的JOIN语句

时间:2015-12-11 10:44:32

标签: mysql join

我正在努力与MySQL合并两张桌子。

第一个表是客户的子集,名为" merge1 ",并包含以下记录:

    customer_id   First Name      Total Spent    Total Orders
    ==========================================================
    1              Mike              0.00          0.00
    2              Allan             0.00          0.00
    3              Craig             0.00          0.00
    4              Michael           0.00          0.00

表2包含销售数据,如下所示,名为" merge2 ",并包含以下记录:

    customer_id   Total Spent   Total Orders
    =========================================
    1                65.00            1
    2                64.00            1
    3               109.00            1
    4                65.00            1

我试图更新" Total Spent"和"总订单"在第一个表(合并1)中通过runninng以下SQL:

    INSERT INTO `merge1` (`customer_id`, `Total Spent`, `Total Orders`)

    SELECT 
        merge2.`customer_id`,
        merge2.`Total Spent`,
        merge2.`Total Orders`

    FROM  
      merge2

    JOIN
        merge1 ON merge2.customer_id = merge1.customer_id;

查询没有输出错误,但表格没有更新。

有人能指出我正确的方向吗,我非常感谢你的帮助!?

答案

感谢下面的评论!我应该使用"更新"命令。这是我使用的语法,如果它为其他人派上用场。

    UPDATE merge1 T1 JOIN merge2 T2
    SET    T1.`Total Spent` = T2.`Total Spent`, T1.`Total Orders` = T2.`Total Orders`
    WHERE  T1.customer_id = T2.customer_id;

1 个答案:

答案 0 :(得分:0)

嘿,如果你需要插入然后使用:

INSERT INTO `merge1`(`customer_id`, `Total Spent`, `Total Orders`) SELECT 
        merge2.`customer_id` AS customer_id,merge2.`Total Spent` AS Total Spent,merge2.`Total Orders` AS Total Orders FROM merge2

或者,如果你需要更新,那么你:

UPDATE `merge1` JOIN `merge2` ON merge1.customer_id = merge2.customer_id
SET merge1.`Total Spent` = merge2.`Total Spent`,merge1.`Total Orders` = merge2.`Total Orders`

让我知道会发生什么:)