MySQL insert data from other table

陌路散爱 提交于 2020-01-05 13:06:37

问题


This question is similar to my previous question except this is INSERT instead of update I have two tables: contacts and companies.

contacts has : id, group_id, company_id, email, company
companies has: id, group_id, name, email

so using this query

UPDATE contacts c
INNER JOIN companies co ON c.company_id = co.id 
SET c.group_id = co.group_id,
    c.company = companies.name

I can move update data from company to contacts where there contact.company_id = company.id.

But how can I do INSERT instead for all the company where does not have contact yet? or to make things simpler, how can I move all companies table data into contacts table data. e.g:

Companies
id   group_id   name   email
1    1          abc    a@a.com
2    1          def    d@d.com
3    1          ghi    g@g.com

Contacts
id   group_id   company_id   email     company   phone
1    1          1            a@a.com   abc
2    1          2            d@d.com   def
3    1          3            g@g.com   ghi

So I would like the entry like that, and for the one that is no value will be default to NULL or None


回答1:


I think that you want:

INSERT INTO Contacts (id,group_id,company_id,email,name)
SELECT co.id,co.group_id,co.id,co.email,co.name
FROM company co
LEFT JOIN contacts c ON co.id = c.company_id
WHERE c.company_id IS NULL

This will insert all the information from contacts in company that wasn't already there. the column phone will be left null, since there is no information in contacts for that column.




回答2:


I believe you would need to do an outer join between the 2 tables in your select statement then look for a field in your destination table to be null and only select those rows.

insert into t1 (f1,f2,f3) select s1,s2,s3 from sourcetable as st 
  left outer join t1 on 
      t1.f1=st.s1,
      t1.f2=st.s2,
      t1.f3=st.s3
  where t1.id is null;

This way you only get the rows from st where there is no id in t1.



来源:https://stackoverflow.com/questions/20388635/mysql-insert-data-from-other-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!