我在表中有一个名为names的字段。该字段显示“last_name,first_name”。我试图从名称表中取出该字段,并将值插入到一个新表中,分为2个标记为last_name和first_name的不同列。我尝试过以下代码:
INSERT INTO usernames (last_name,first_name)
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',1),',',-1) as last_name,
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',2),',',-1) as first_name
FROM person;
和
INSERT INTO usernames (last_name,first_name)
SELECT IF(LOCATE(', ',name)>0
SUBSTRING(name,1,LOCATE(', ',name)-1) AS last_name,
IF(LOCATE(', ',name)>0
SUBSTRING(name,LOCATE(', ',name)+1),NULL) AS first_name
FROM person;
我不确定这段代码我做错了什么。任何帮助非常感谢。
谢谢你, 拉里
答案 0 :(得分:1)
您的查询几乎没问题,但不需要第二个SELECT。检查文档中SELECT的语法。
INSERT INTO usernames (last_name,first_name)
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',1),',',-1) as last_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',2),',',-1) as first_name
FROM person;