UPDATE 2 columns in all rows using VALUES() array - mysql

I cant quite figure out the correct way to do the following:
1.) I have a fullname column
2.) I need to split that fullname column into first & last name chunks
3.) I need to insert the 'split' data into their respective columns (which are currently empty and in the same table)
I couldnt figure out how to do it in one query, so I broke it down into steps:
1.) got my split data (first/last strings)
SELECT fullname, SUBSTRING_INDEX(fullname,' ',1) AS fname, SUBSTRING_INDEX(SUBSTRING_INDEX(fullname,'.',2),' ',-1) AS lname FROM tablename;
which gave my fname & lname sub-strings..
I erroneously tried this:
INSERT INTO paypalRegistration (firstname, lastname) VALUES
("xxxx", "xxx"),
("yyy", "yyy"),
("zzz", "zzz"),...etc..
which just insert things into NEW rows.. (and didnt update the current rows [with blank columns] already in the table)
So I then tried this:
UPDATE paypalRegistration SET(firstname, lastname) VALUES ("xxxx", "xxx"),
("yyy", "yyy"), ("zzz", "zzz"),...etc..
but got an error..
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 '(firstname, lastname) VALUES ("xxxx", "xxx").....
So at this point, my question is two-fold.
1.) How can I do this in 1 query?
2.) At the point I'm at, what is the correct way to update 2+ columns with unique values like I have above?
Update:
This is what worked for me in the end:
UPDATE myTable SET firstname=SUBSTRING_INDEX(fullname,' ',1), lastname=SUBSTRING_INDEX(SUBSTRING_INDEX(fullname,'.',2),' ',-1);

Say your table name is paypalRegistration
This table paypalRegistration has the following columns:
id INT PRIMARY KEY
fullName VARCHAR
firstName VARCHAR
lastName VARCHAR
I expect to have id column already in your table paypalRegistration as explained above.
Now, you can do this SQL:
UPDATE paypalRegistration x
INNER JOIN (
SELECT
id,
SUBSTRING_INDEX(fullName,' ',1) AS fname,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullName,'.',2),' ',-1) AS lname
FROM paypalRegistration
) y ON y.id=x.id
SET x.firstName = y.fname, x.lastName = y.lname;

Related

How to use select statement to insert values on a table

I am trying to insert theses values to my table student but I have an error
insert into student(first_name,last_name,student_number,professor_id)
values(Eden,Yuan,323744573,
select professor_id from PROFESSORS where professor_name = 'Chu ')
I get an error
saying missing expression
you can use this way (assuming that professor_id is the column you need)
insert into student(first_name,last_name,student_number,professor_id)
select 'Eden', 'Eden', 323744573, column_professor_id
from PROFESSORS where professor_name = 'Chu ' ;
(In your query is missing the column in the select )

how to concat two columns into one with the existing column name in mysql?

I want to concatenate two columns in a table with a existing column name using mysql.
An example: I am having a column FIRSTNAME and LASTNAME and so many columns also. I want to concatenate these two columns with the name of FIRSTNAME only.
So I tried like this:
SELECT *, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;
but it displaying the two fields with the name of FIRSTNAME. one field is having normal values and another one is having concatenated values. I want only one column with those concatenate value. I can select single columns, but am having more than 40 columns in my table.
Is there any way to remove the original column using mysql itself?
As aziz-shaikh has pointed out, there is no way to suppress an individual column from the * directive, however you might be able to use the following hack:
SELECT CONCAT(c.FIRSTNAME, ',', c.LASTNAME) AS FIRSTNAME,
c.*
FROM `customer` c;
Doing this will cause the second occurrence of the FIRSTNAME column to adopt the alias FIRSTNAME_1 so you should be able to safely address your customised FIRSTNAME column. You need to alias the table because * in any position other than at the start will fail if not aliased.
Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.
You can use the SQL statement something like:
SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;
BTW, why couldn't you use FullName instead of FirstName? Like this:
SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;
You can try this simple way for combining columns:
select some_other_column,first_name || ' ' || last_name AS First_name from customer;
Remove the * from your query and use individual column names, like this:
SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;
Using * means, in your results you want all the columns of the table. In your case * will also include FIRSTNAME. You are then concatenating some columns and using alias of FIRSTNAME. This creates 2 columns with same name.
Just Remove * from your select clause, and mention all column names explicitly and omit the FIRSTNAME column. After this write CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME.
The above query will give you the only one FIRSTNAME column.
I am a novice and I did it this way:
Create table Name1
(
F_Name varchar(20),
L_Name varchar(20),
Age INTEGER
)
Insert into Name1
Values
('Tom', 'Bombadil', 32),
('Danny', 'Fartman', 43),
('Stephine', 'Belchlord', 33),
('Corry', 'Smallpants', 95)
Go
Update Name1
Set F_Name = CONCAT(F_Name, ' ', L_Name)
Go
Alter Table Name1
Drop column L_Name
Go
Update Table_Name
Set F_Name

Replacing the single quotes for columns in select statement in SQL Server

I have 2 tables. In table1 I have some rows for persons like this:
PersonX - ID
PersonX - Name
PersonX - Address
PersonY - ID
PersonY - AGE
In 2nd table, above mentioned ID, NAME,ADDRESS,AGE will be columns. And we have detailed data of personX and PersonY here.
Now, main issue is in stored procedure, using cursor, I am storing table1 values ('ID', 'Name', ...) in a variable #Element.
Now I am using select statement in same cursor as below:
SELECT #Element From Table2
I need output of user details like his id, age, address etc. But instead I am getting output as 'ID', 'NAME', 'AGE' etc....
I found that this is because #Element is varchar and has string value, so select statement is executed as below:
SELECT 'ID' from table2.
but all I need is like below
SELECT ID FROM TABLE2
I used replace function its not working for me. Case function, I can't use it because we can't say what data is there for a person in table1. It varies. I need one dynamic statement which can be use for all records. instead of executing case for each record.
SELECT REPLACE(#Element,'''','')
FROM TABLE2
(Still getting 'ID' as output, instead of corresponding value in Table2)
Please help me in this. Hope you understand my explanation
You will need to use dynamic SQL to achieve this, for example:
CREATE TABLE Table1
(
ID INT
,Name VARCHAR(255)
,ADDRESS VARCHAR(255)
)
INSERT Table1 VALUES ('1','Joe Bloggs','Address 1')
INSERT Table1 VALUES ('2','Jane Doe','Address 2')
DECLARE #ColName VARCHAR(255) = 'ID'
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'SELECT '+#ColName+','+''''+#ColName+''' FROM TABLE1'
EXEC (#SQL)
In the first column that is returned, is the SQL you want to be able to execute, however in the 2nd column in my query, is what you're doing at the moment. As far as SQL is concerned, your variable is simply storing a value. It does not know you are referring to a column name which is why it simply returns the value.

MySQL Populate a new field with query results from another field in the same table

I have a large (1 million + row) database/table that includes a "Name" field. However, I need a firstname and lastname field.
I am able to run queries to display the fist and last names the way I need them in the new fields (parsing), but I can't seem to get those query results to INSERT into the table.
I was able to create the fields in the table, but not populate them.
I am working in phpMyAdmin, and the table was exported from Access via ODBC.
A couple examples of code that doesn't work are below. It's been a few years since I had to work with SQL and I think maybe the logic of this approach is just wrong. I certainly appreciate any help.
Example that doesn't work:
INSERT INTO fed2012_aquabarndesign_com (lastname)
select left(Name,InStr(Name,',')) AS lastname
from fed2012_aquabarndesign_com
or
INSERT INTO fed2012_aquabarndesign_com (lastname)
Values (select left(Name,InStr(Name,',')) from fed2012_aquabarndesign_com);
Here's how you can do it with an UPDATE -- not sure you want to INSERT those records back to the same table:
update fed2012_aquabarndesign_com
set firstname = trim(left(name, instr(name, ' ' ))),
lastname = trim(right(name, length(name) - instr(name, ' ' )))
SQL Fiddle Demo
This does assume each full name has a space in between the first name and last name fields.
If you really want to reinsert those rows, then this should work:
insert into fed2012_aquabarndesign_com (firstname, lastname)
select trim(left(name, instr(name, ' ' ))),
trim(right(name, length(name) - instr(name, ' ' )))
from fed2012_aquabarndesign_com;
SQL Fiddle Demo

MySQL Conditional Insert. Works in phpMyAdmin but not PHP Script

I am trying to create a conditional INSERT into my MySQL databate from a PHP script. The following SQL syntax works in phpMyAdmin, but not in my PHP Script:
INSERT INTO profiles (id, firstname)
SELECT "22","John" from profiles
WHERE NOT EXISTS (
SELECT * FROM li_profiles
WHERE li_p_firstname = "John"
)
(Note that "id" is the primary key, "firstname" is not a key or unique)
Something weird that might be part of the issue is that when I run that SQL in phpMyAdmin, while it does "work" (meaning that a new record is added with the id "22" and the firstname "John") I get the following warning: "#1062 - Duplicate entry '22' for key 1"
But the table didn't have a previous entry with id of 22. ??!!
What's going on?
Change SELECT to VALUES
INSERT INTO profiles (id, firstname) VALUES("22","John") FROM profiles WHERE NOT EXISTS ( SELECT * FROM li_profiles WHERE li_p_firstname = "John" )
Also, if you are using auto-increment values, you should specify the next value. Also, if its an integer, give an integer (22) not a string ("22")
You'll get a duplicate entry for the iD because you are inserting a new row for each row in the profiles table; for every row in the profiles table there is no John in the li_profiles table. You might try
INSERT INTO profiles (id, firstname)
SELECT "22","John" from profiles
WHERE NOT EXISTS (SELECT * FROM li_profiles
WHERE li_p_firstname = "John")
LIMIT 1;
which would eliminate the duplicate problem (if it works, sorry but I haven't checked this myself).
I figured it out in a different way. (I'm told that the HAVING statement is slow, so I'm not sure that it's the best way... but it the only method I've gotten to work.)
INSERT INTO profiles (id,firstname)
SELECT 22,'John'
FROM li_profiles
WHERE firstname = 'John'
HAVING COUNT(*) = 0;