更新表A.type = B.type WHERE A.id = B.id

时间:2013-05-28 19:03:21

标签: mysql

我在不同的数据库中有两个表:

在名为CRMALPHA的数据库中:

CREATE TABLE IF NOT EXISTS `contacts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `accountId` int(11) NOT NULL,
  `Type` int(11) NOT NULL,
  `fName` varchar(255) NOT NULL,
  `lName` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `workPhone` int(11) NOT NULL,
  `workPhoneExt` int(11) NOT NULL,
  `cellPhone` int(11) NOT NULL,
  `altPhone` int(11) NOT NULL,
  `altPhoneDescription` varchar(255) NOT NULL,
  `dob` date NOT NULL,
  `createdDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `createdById` int(11) NOT NULL,
  `notes` varchar(255) NOT NULL,
  `isDeleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `accountId` (`accountId`,`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=12006 ;

在名为scottse1_lifestyle_test

的数据库中
CREATE TABLE IF NOT EXISTS `tbl_customers_contact_types` (
  `ContactId` int(4) NOT NULL DEFAULT '0',
  `TypeId` int(5) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ContactId`,`TypeId`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

我需要:

UPDATE crmalpha.contacts 
SET type = scottse1_lifestyle_test.tbl_customers_contact_types.TypeID 
WHERE scottse1_lifestyle_test.tbl_customers_contact_types.ContactId = crmalpha.contacts.id

这会导致以下错误:

#1054 - Unknown column 'scottse1_lifestyle_test.tbl_customers_contact_types.ContactId' in 'where clause'

我做错了什么?

修改

解决方案是:

UPDATE crmalpha.contacts c
JOIN scottse1_lifestyle_test.tbl_customers_contact_types t
ON t.ContactId = c.id
SET c.type = t.TypeId

1 个答案:

答案 0 :(得分:0)

您必须以逗号分隔的方式选择表格:

UPDATE CRMALPHA.contacts, scottse1_lifestyle_test.tbl_customers_contact_types
SET Type = scottse1_lifestyle_test.tbl_customers_contact_types.TypeID 
WHERE scottse1_lifestyle_test.tbl_customers_contact_types.ContactId = CRMALPHA.contacts.id