I have a drupal database where the node
table is full of profiles. The field node.tit开发者_StackOverflow社区le
is "Firstname Lastname". I want to separate the names so that node.title
= "Firstname", and over in another table entirely, content_type_profile.field_lastname_value
= "Lastname". The entries in the two tables can be joined on the field nid
.
I'd love to run a SQL command to do this, and I am fine with taking the naive approach that the first word is the first name, and everything else in the field is last name -- it will mean a few manual corrections down the line, but that's much better than doing it all by hand in the first place.
(I read this question and surely the answer lies in there but I am not that SQL-savvy and am not sure how to make it work for my database.)
Thanks!
You can replace 'John Smith' with the actual column name from your table, but this should give you the general idea.
select substring('John Smith',1,instr('John Smith',' ')-1) first_name;
select substring('John Smith',instr('John Smith',' ')+1) last_name;
EDIT:
Here's a complete working example. I did it on Oracle since I don't have drupal, but hopefully the syntax should be similar.
CREATE TABLE content_type_profile (nid number,field_lastname_value VARCHAR2(20));
CREATE TABLE node (nid number,title VARCHAR2(20))
DELETE FROM node;
INSERT INTO node VALUES (1, 'John Smith');
INSERT INTO node VALUES (2, 'Jane Doe');
DELETE FROM content_type_profile;
INSERT INTO content_type_profile VALUES (1,NULL);
INSERT INTO content_type_profile VALUES (2,NULL);
UPDATE content_type_profile c
SET field_lastname_value =
(SELECT SUBSTR(n.title,instr(n.title,' ')+1)
FROM node n
WHERE n.nid = c.nid);
SELECT * FROM content_type_profile;
// returns 2 rows, one for Smith and one for Doe
UPDATE node
SET title = SUBSTR(title,1,instr(title,' ')-1);
SELECT * FROM node;
// returns 2 rows, one for John and one for Jane
精彩评论