如何在不覆盖的情况下将2个表组合成第三个表SQL?

时间:2018-01-17 13:13:12

标签: php mysql sql phpmyadmin

所以我有3个Sql表,我运行这个命令

INSERT INTO `wp_atkv_EWD_OTP_Customers` (`Customer_ID`,`Customer_Email`,`Customer_Created`) 
SELECT 
    `User_ID`, 
    `Username` , 
    `User_Date_Created` 
FROM `wp_atkv_EWD_FEUP_Users`

并且它工作得很好我想使用相同的用户ID从另一个表添加数据但是然后我运行下面的命令它说重复错误?我不应该使用插入吗?如果我忽略了副本,它只会创建新的条目,我希望它们都在同一行

INSERT INTO `wp_atkv_EWD_OTP_Customers` (`Customer_ID`,`Customer_Name`) 
SELECT 
    `User_ID`, 
    group_concat(`Field_Value`) 
FROM `wp_atkv_EWD_FEUP_User_Fields` 
GROUP by `User_ID`

我该怎么办?如何使用第三张表更新?

1 个答案:

答案 0 :(得分:1)

我期待join

INSERT INTO wp_atkv_EWD_OTP_Customers (Customer_ID, Customer_Email, Customer_Created, Customer_Name)
    SELECT u.User_ID, u.Username, u.User_Date_Created, uf.vals
    FROM wp_atkv_EWD_FEUP_Users u LEFT JOIN
         (SELECT User_ID, group_concat(Field_Value) as vals 
          FROM wp_atkv_EWD_FEUP_User_Fields
          GROUP by User_ID
         ) uf
         ON u.user_id = uf.user_id;

或者,您可能需要update

update wp_atkv_EWD_OTP_Customers c join
       (select `User_ID`, group_concat(`Field_Value`) as vals
        from `wp_atkv_EWD_FEUP_User_Fields` 
        group by `User_ID`
       ) uf
       on c.customer_id_id = cf.user_id
    set Customer_Name = uf.vals;