首页 > 解决方案 > 如果第二个表具有条件值,则插入表中

问题描述

我有两张桌子:

表1(客户)

customer_id   customer_name  salesPerson_id
1             John           1
2             Ed             1
3             Sam            2

表 2 (customerContacts)

contact_id   customer_id  phone_number
1            1            687-5309
2            1            555-1234
3            1            742-1111

我试图只让销售人员为其特定客户添加/更新电话号码。

所以只有 sales salesPerson_id 1 可以更新 John 和 Ed,只有 salesPerson_id 2 可以更新 Sam。

我相信我正在寻找类似的东西:

INSERT INTO customerContacts (contact_id , customer_id , phone_number) VALUES (1 , 1 , '987-6543')
ON DUPLICATE KEY UPDATE phone_number='987-6543'
    IF customers.salesPerson_ID = 1

但似乎 sql 不支持 if 语句。

标签: mysqlsql

解决方案


INSERT INTO customerContacts (contact_id , customer_id , phone_number) 
    Select 1 , customer_id , '987-6543' 
    from customers
    where salesPerson_ID = 1 and customer_id=1;

这是您应该以本机方式使用的查询,但您需要将其放入您的应用程序框架中


推荐阅读