来自另一个表的MySQL更新表

时间:2013-12-03 18:59:33

标签: php mysql sql database sql-update

我有两张桌子:联系人和公司。

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

目前,contacts.group_id值为0(最近添加了列),所以contacts.company值为“”。

我应该如何移动数据

companies.group_id to contacts.group_id and companies.name to contacts.company 
based on contacts.company_id = companies.id?

我尝试了以下查询,但却给了我错误

UPDATE contacts SET contacts.group_id=companies.group_id 
FROM companies WHERE contacts.company_id=companies.id;

它给了我这个错误

#1064 - You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version 
for the right syntax to use near 'FROM companies WHERE 
contacts.company_id=companies.id' at line 1

我使用phpmyadmin来运行此查询

2 个答案:

答案 0 :(得分:2)

Mysql允许你在UPDATE语句中执行JOINS:

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

来自docs

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]
  

您还可以执行覆盖多个表的UPDATE操作。   但是,您不能将ORDER BY或LIMIT与多表一起使用   UPDATE。 table_references子句列出了连接中涉及的表。

答案 1 :(得分:1)

我认为这对您有用:

update
  contacts,
  companies
set
  contacts.group_id=companies.group_id, 
  contacts.company=companies.name
where
  contacts.company_id = companies.id