SQL substring() matching first letter in first- and lastname - mysql

I am a beginner of the SQL language and wonder a little about how I can match names from my database that has the same first letter in
first- and lastname ?
For exemple:
Alex Andersen
Alice Aaronson
Brad Baalman
Brett Baren
Chris Cat
And so forth...
My code is:
SELECT substring(firstname,1) AS first_letter
AND substring(lastname,1) AS first_letter
FROM kids
ORDER BY firstname

Use WHERE to filter records:
SELECT *
FROM kids
WHERE LEFT(firstname, 1) = LEFT(lastname, 1)
ORDER BY firstname;
or:
SELECT *
FROM kids
WHERE SUBSTRING(firstname, 1, 1) = SUBSTRING(lastname, 1, 1)
ORDER BY firstname;

Related

return mid string and count

I have a concatenated string in a field that I now need to pull statistics from.
What is needed is a count of how many records are from each county in Maryland.
fieldname county_city is stored as follows:
Frederick,MD - Frederick County - 21701
//State
trim(substring(SUBSTRING_INDEX(county_city,',',-1),1,3)) as state
//city
SUBSTRING_INDEX(county_city,'-',1) as city_state
//zip code
SUBSTRING_INDEX(county_city,'-',-1) as zipcode,
but getting the county has been eluding me!
I have an idea that getting the count will elude me as well.
With string functions is a 2 step procedure:
set #s = 'Frederick,MD - Frederick County - 21701';
SELECT TRIM(SUBSTRING_INDEX(SUBSTRING(#s, LENGTH(SUBSTRING_INDEX(#s, '-' ,1)) + 2), '-', 1));
See the demo.
Result:
Frederick County

Concat a string to a field value into a table

I want to add a string i.e "Building " to each random name of my table.
I tried concat, & and +
UPDATE officine
SET nom = (SELECT fake_name.last_name
FROM fake_name
ORDER BY rand()
LIMIT 1);
I have actually :
Dupont
March
and I would like to get
Building Dupont
Building March
Something like this?
UPDATE officine
SET nom = (SELECT CONCAT('Building ', fake_name.last_name)
FROM fake_name
ORDER BY rand()
LIMIT 1
);

Separate Columns with conditions

I have a table with some problem data. For example, the table is as follow :
ID NAME JOB
--- --------------------------- ---------------
1 Peter Teacher
2 John Programmer
3 Tom**He is a Teacher
4 Alan**He is a Accountant
The problem is some data has been correctly inserted but some hasn't. Now I want to execute an SQL in order to make the table looks like below :
ID NAME JOB
--- --------------------------- ---------------
1 Peter Teacher
2 John Programmer
3 Tom Teacher
4 Alan Accountant
I am not familiar with SQL Statement so I can just think of using the following PHP Script to fix this problem.
$sql1 = "SELECT NAME FROM MY_TABLE WHERE JOB = '' AND NAME LIKE '%He is a %'";
$res1 = mysql_query($sql1);
while($row1 = mysql_fetch_array($res1)){
$new_data = explode("**He is a ", $row1["NAME"]);
$sql2 = "UPDATE MY_TABLE SET NAME = '".$data[0]."', JOB = '".$data[1]."' WHERE ID = '".$data["ID"]."'";
mysql_query($sql2);
}
Can anyone suggest a better way for me to fix this problem with one or a few SQL Statement ? Thanks
UPDATE
SET NAME = SUBSTRING_INDEX(SUBSTRING_INDEX(NAME, '**He is a ', 1), ' ', -1),
job = SUBSTRING_INDEX(SUBSTRING_INDEX(NAME, '**He is a ', 2), ' ', -1)
WHERE NAME LIKE '%**He is a %'
You can use the substring_index function to break up the string, and apply all the changes in a single update statement:
UPDATE my_table
SET JOB = SUBSTRING_INDEX (name, '**He is a ', -1),
name = SUBSTRING_INDEX (name, '**He is a ', 1),
WHERE name LIKE '%**He is a %' AND
(job IS NULL OR job = '') -- Just to be on the safe side

How to split the string in one column into two columns

I have a table like this
id value
------- ---------------
1 ind.kolkatta
2 ind.pune
3 ind.mumbai
4 pak.lahore
5 pak.karachi
6 uae.sharjah
I want to return the following table:
id contry place
------- --------- ----------
1 ind kolkatta
2 ind pune
3 ind mumbai
4 pak lahore
5 pak karachi
6 uae sharjah
how can i do that using MSSQL.? I have already done in MYSQL using SUBSTRING_INDEX function
My MySql query
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, '.', 1), '.', -1) as contry,
SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, '.', 2), '.', -1) as place
FROM `table`
Try following query:-
SELECT ID, SUBSTRING(value, 1, CHARINDEX('.', value)-1) AS contry,
SUBSTRING(value, CHARINDEX(',', value)+1, LEN(value)) AS place
FROM YOUR_TABLE;
This might be helpful to you.
Hope the Below Query helps you.
SELECT id, SUBSTRING(value,1,3) as Country,SUBSTRING(value,4,LEN(value))AS Place FROM TableName
Try this:
SELECT Id,
LEFT(Value, CHARINDEX('.', Value)-1) AS Country,
STUFF(Value, 1, CHARINDEX('.', Value), '') AS Place
FROM Table
As per King King comment I checked the following
SELECT Id,
PARSENAME(value, 2) AS Country,
PARSENAME(Value, 1) AS Place
FROM Table
The above one worked, but I not sure about the version supported (I am using SSMS 2012).
Or just loop and it will parse out how ever many periods you have in your name.
DECLARE #FILE VARCHAR(55) = 'ind.kol.katta.test1.test2.test3.test4'
DECLARE #FILEFUN AS VARCHAR(55) = LEFT(#FILE,CHARINDEX('.',#FILE))
DECLARE #FILENAMEOUTPUT AS TABLE(Name Varchar(55))
WHILE LEN(#FILE) > 0
BEGIN
INSERT INTO #FILENAMEOUTPUT
SELECT REPLACE(#FILEFUN,'.','')
SET #FILE = REPLACE(#FILE,#FILEFUN,'')
SET #FILEFUN = iif(CHARINDEX('.',#FILE)=0,#FILE,LEFT(#FILE,CHARINDEX('.',#FILE)))
END
SELECT * FROM #FILENAMEOUTPUT

Detect double value in MySQL

I have an InnoDB table with fields
firstname, lastname
While displaying names, usually only firstname is enough. Sometimes users have the same first name; so I have to get firstname and first letter of lastname:
CONCAT(firstname, ' ', SUBSTRING(lastname, 1, 1), '.')
Is there a (performant) way to only display the first letter of the last name in case of a double first name? Something like
WHEN isDouble(Firstname) THEN
CONCAT(firstname, ' ', SUBSTRING(lastname, 1, 1), '.')
ELSE firstname
/* edit */
Forgot to mention the solution I was thinking of:
Creating a column 'double_firstname', with value 1 or 0, and use a CASE statement to select. Then update the double_firstname column on user create and delete.
You can of course ask mysql if the number of entries for that firstname is bigger than one, so:
select IF( (select count(*) as cnt from person where firstname = p.firstname) > 1
, concat(firstname, " ", substring(lastname, 1))
, firstname)
from person
where id = 4711
;
But that is not very quick.
Better for a higher number of persons is a stable mark on person how to "call" her. That could be "firstname lastname" initially and then get more personally with reducing to firstname by a cronjob. It also could mean to call "John Doe" just John, because he entered early, and "John DaSecond" call "John D.", and "JohnDaThird" call "John DaT.".
JohnD is not unique in that scenario.
Is John Doe informed about being renamed to "John D." in your Scenario?
You asked for good performance as well as the ability to do it. If you have an index on names(firstname, lastname) the following should perform well:
select (case when exists (select 1
from names n2
where n2.firstname = n.firstname and n2.lastname <> n.lastname
)
then concat(firstname, ' ', left(lastname, 1))
else firstname
end)
from names n