简体   繁体   中英

Insert into table if second table has conditional value

I have two tables:

Table 1 (customers)

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

Table 2 (customerContacts)

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

I am trying to let only the sales person add / update a phone number for their specific customer.

So only sales salesPerson_id 1 could update John and Ed and only salesPerson_id 2 could update Sam.

I believe I am looking for something like:

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

But it doesn't seem like sql supports if statements.

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;

This is the query which you should use in the native way but you need to fit this in your application framework

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM