表格:
CREATE TABLE `vendor_contacts` (
`vendor_id` int(11) NOT NULL,
`last_name` varchar(50) NOT NULL,
`first_name` varchar(50) NOT NULL,
`name_initials` varchar(45),
PRIMARY KEY (`vendor_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
使用以下insert语句:
INSERT INTO `vendor_contacts`
VALUES (5,'Davison','Michelle',''),
(12,'Mayteh','Kendall',''),
(17,'Onandonga','Bruce',''),
(44,'Antavius','Anthony',''),
(76,'Bradlee','Danny',''),
(94,'Suscipe','Reynaldo',''),
(101,'O\'Sullivan','Geraldine',''),
(123,'Bucket','Charles','');
我正在尝试使用以下命令分配列,name_initials,派生自PostgreSQL [Update> Set> From]:
UPDATE vendor_contacts
SET name_initials = t.initials
FROM (
SELECT vendor_id, last_name, first_name,
CONCAT(LEFT(first_name, 1), LEFT(last_name, 1)) as initials
FROM vendor_contacts;
) t
WHERE vendor_id = t.vendor_id;
由于这不起作用,我尝试了Oracle SQL Merge Into:
MERGE INTO vendor_contacts
USING (
SELECT vendor_id, last_name, first_name,
CONCAT(LEFT(first_name, 1), LEFT(last_name, 1)) as initials
FROM vendor_contacts;
) t
ON (vendor_id = t.vendor_id)
WHEN matched THEN
UPDATE SET name_initials = t.initials;
MERGE不起作用。
我尝试了一个子查询,它也不起作用:
UPDATE vendor_contacts vc
SET name_initials = (SELECT CONCAT(LEFT(first_name, 1), LEFT(last_name, 1))
FROM vendor_contacts vcsq
WHERE vcsq.vendor_id = vc.vendor_id);
答案 0 :(得分:2)
为什么所有这些并发症,为什么不呢?
UPDATE vendor_contacts
SET name_initials = CONCAT(LEFT(first_name, 1), LEFT(last_name, 1));
它根据其他列的值设置首字母字段。
但即使这个查询也是你不应该运行的东西。正确的做法是删除name_initials
列。你不需要它。因为它是简单计算的结果,通常不会为简单计算创建列。您可以使用生成的列,也可以使用简单的。
SELECT *,
CONCAT(LEFT(first_name, 1), LEFT(last_name, 1)) AS name_initials FROM vendor_contacts;