CASE WHEN does not exist on Access SQL - mysql

I discovered a couple of hours ago that CASE WHEN doesn't work on access queries. I have a complex CONCAT on my SELECT statement but it is written in MySQL:
SELECT CONCAT(
'www.mywebsite.com/catalogsearchtool?title='
, REPLACE(tblTitles.Content_Name, '&', '%26')
, '&contributor=ln:'
, CASE WHEN LOCATE('; ',tblTitles.Contributors) > 0
THEN REPLACE(REPLACE(REPLACE(
CASE WHEN RIGHT(TRIM(tblTitles.Contributors), 1) = ',' THEN LEFT(TRIM(tblTitles.Contributors), CHAR_LENGTH(TRIM(tblTitles.Contributors)) - 1) ELSE TRIM(tblTitles.Contributors) END
, '&', '%26'), '; ', ',rl:Author&contributor=ln:'), ', ', ',fn:')
ELSE REPLACE(REPLACE(
CASE WHEN RIGHT(TRIM(tblTitles.Contributors), 1) = ',' THEN LEFT(TRIM(tblTitles.Contributors), CHAR_LENGTH(TRIM(tblTitles.Contributors)) - 1) ELSE TRIM(tblTitles.Contributors) END
, '&', '%26'), ', ', ',fn:')
END
, ',rl:Author&language='
, LOWER(tblTitles.language)
) AS 'link'
Basically what that does is that it generates a link based on names that can be found in a column called Contributors. That column has the following order:
last_name, first_name
or
last_name, first_name; last_name, first_name
For reasons out of my control, there can be many names in that column. So for the query above a couple of results would be (for 2 names):
www.mywebsite.com/catalogsearchtool?title=tile123&contributor=ln:smith,fn:john,rl:Author&contributor=ln:smith,fn:jane,rl:Author&language=english
And (for 1 name):
www.mywebsite.com/catalogsearchtool?title=title5678&contributor=ln:smith,fn:john,rl:Author&language=english
Can anyone please help me translating this logic to Access SQL?

Related

How to improve slow query performance?

I have a multi-join query that targeting the hospital's chart database.
this takes 5~10 seconds or more.
This is the visual expain using mysql workbench.
The query is below.
select sc.CLIENT_ID as 'guardianId', sp.PET_ID as 'patientId', sp.NAME as 'petName'
, (select BW from syn_vital where HOSPITAL_ID = sp.HOSPITAL_ID and PET_ID = sp.PET_ID order by DATE, TIME desc limit 1) as 'weight'
, sp.BIRTH as 'birth', sp.RFID as 'regNo', sp.BREED as 'vName'
, (case when ss.NAME like '%fel%' or ss.NAME like '%cat%' or ss.NAME like '%pawpaw%' or ss.NAME like '%f' then '002'
when ss.NAME like '%canine%' or ss.NAME like '%dog%' or ss.NAME like '%can%' then '001' else '007' end) as 'sCode'
, (case when LOWER(replace(sp.SEX, ' ', '')) like 'male%' then 'M'
when LOWER(replace(sp.SEX, ' ', '')) like 'female%' or LOWER(replace(sp.SEX, ' ', '')) like 'fam%' or LOWER(replace(sp.SEX, ' ', '')) like 'woman%' then 'F'
when LOWER(replace(sp.SEX, ' ', '')) like 'c.m%' or LOWER(replace(sp.SEX, ' ', '')) like 'castratedmale' or LOWER(replace(sp.SEX, ' ', '')) like 'neutered%' or LOWER(replace(sp.SEX, ' ', '')) like 'neutrality%man%' or LOWER(replace(sp.SEX, ' ', '')) like 'M.N%' then 'MN'
when LOWER(replace(sp.SEX, ' ', '')) like 'woman%' or LOWER(replace(sp.SEX, ' ', '')) like 'f.s%' or LOWER(replace(sp.SEX, ' ', '')) like 'S%' or LOWER(replace(sp.SEX, ' ', '')) like 'neutrality%%' then 'FS' else 'NONE' end) as 'sex'
from syn_client sc
left join syn_tel st on sc.HOSPITAL_ID = st.HOSPITAL_ID and sc.CLIENT_ID = st.CLIENT_ID
inner join syn_pet sp on sc.HOSPITAL_ID = sp.HOSPITAL_ID and sc.FAMILY_ID = sp.FAMILY_ID and sp.STATE = 0
inner join syn_species ss on sp.HOSPITAL_ID = ss.HOSPITAL_ID and sp.SPECIES_ID = ss.SPECIES_ID
WHERE
trim(replace(st.NUMBER, '-','')) = '01099999999'
and trim(sc.NAME) = 'johndoe'
and sp.HOSPITAL_ID = 'HOSPITALID999999'
order by TEL_DEFAULT desc
I would like to know how to improve the performance of this complex query.
The most obvious performance killers in your query are the non-sargable criteria in your where clause.
trim(replace(st.NUMBER, '-','')) = '01099999999'
This cannot use any available index as you have applied a function to the column, which needs to be evaluated before the comparison can be made.
As suggested by Pham, you could change your criterion to -
st.number IN ('01099999999', '01-099-999-999', 'ALL_OTHERS_FORMAT_YOU_ACCEPTS...')
or better still would be to normalize the numbers before you store them (you can always apply formatting for display purposes), that way you know how to search the stored data. Strip all the hyphens and spaces from the existings numbers -
UPDATE syn_tel
SET number = REPLACE(REPLACE(number, '-',''), ' ', '')
WHERE number LIKE '% %' OR number LIKE '%-%';
Similarly for the next criterion -
trim(sc.NAME) = 'johndoe'
The name should be trimmed before being stored in the database so there is no need to trim it when searching it. Update already stored names to trim whitespace -
UPDATE syn_client
SET NAME = TRIM(NAME)
WHERE NAME LIKE ' %' OR NAME LIKE '% ';
Changing sp.HOSPITAL_ID = 'HOSPITALID999999' to sc.HOSPITAL_ID = 'HOSPITALID999999' will allow for the use of a composite index on syn_client (HOSPITAL_ID, name) assuming you drop the TRIM() from the previously discussed criterion.
The sorting in your sub-query for weight might be wrong -
order by DATE, TIME desc limit 1
presumably you want the most recent weight -
order by `DATE` desc, `TIME` desc limit 1
/* OR */
order by CONCAT(`DATE`, ' ', `TIME`) desc limit 1
order by DATE, TIME desc -- really? That's equivalent to date ASC, time DESC. If you want "newest first", then ORDER BY date DESC, time DESC. Furthermore, it is usually bad practice and clumsy to code when you have DATE and TIME in separate columns. Is there a strong reason for storing them separately? It is reasonably easy to split them apart in a SELECT.
Similarly, cleanse NUMBER and NAME when inserting.
This will make the first subquery much faster:
syn_vital needs INDEX(hostital_id, pet_id, date, time, BW)
LIKE with a leading wildcard (%) is slow, but you probably cannot avoid it in this case.
LOWER(replace(sp.SEX, ' ', '')) -- Cleanse the input during INSERT, not on output!.
LOWER(...) -- With a suitable COLLATION (eg, the default), calling LOWER is unnecessary.
Some of these 'composite' INDEXes may be useful:
ss: INDEX(HOSPITAL_ID, SPECIES_ID, NAME)
st: INDEX(HOSPITAL_ID, CLIENT_ID, NUMBER)
sp: INDEX(HOSPITAL_ID, PET_ID)
What table is TEL_DEFAULT in?
You may want to:
Create index on syn_client(hospital_id, name --,tel_default?)
Create index on syn_tel(hospital_id, client_id, number)
Create index on syn_pet(hospital_id, family_id, state)
Create index on syn_species(hospital_id, species_id)
Change your query to:
SELECT ...
FROM syn_client sc
INNER JOIN syn_tel st ON sc.hospital_id = st.hospital_id AND sc.client_id = st.client_id
INNER JOIN syn_pet sp ON sc.hospital_id = sp.hospital_id AND sc.family_id = sp.family_id AND sp.state = 0
INNER JOIN syn_species ss ON sp.hospital_id = ss.hospital_id AND sp.species_id = ss.species_id
WHERE st.number IN ('01099999999', '01-099-999-999', 'ALL_OTHERS_FORMAT_YOU_ACCEPTS...')
AND trim(sc.name) = 'johndoe' --sc.name = 'johndoe' with standardize data input
AND sc.hospital_id = 'HOSPITALID999999' --not sp.hospital_id
ORDER BY tel_default DESC;

Query not returning anything when no last_name value found

I just built this new conditional query for pulling either a first_name AND last_name OR company_name based on the display_as value:
Select If(`display_as` = 'individual',
CONCAT(first_name, ' ', last_name)
,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1
The problem is, if the user has a first_name value only and no value for last_name, nothing is returned at all.
How can I fix this?
use this query instead.
$sql = "Select If(`display_as` = 'individual',
CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, ''))
,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1";
try this one:
Select
If( `display_as` = 'individual',
CONCAT(coalesce(first_name, ''), ' ', coalesce(last_name, ''))
,`company_name`) as name
FROM `{$this->table}`
WHERE `unique_id` = ?
LIMIT 1
I would recommend writing this as:
select (case when display_as = 'individual'
then concat_ws(' ', first_name, last_name)
else company_name
end) as name
from `{$this->table}`
where unique_id = ?
limit 1; -- probably not needed
Notes:
case is the standard SQL construct for conditional logic. if() is a bespoke MySQL extension.
concat_ws() elegantly handles NULL values in the names. It simply ignores the the value rather than returning NULL.
Backticks are not required everywhere. They just make the query harder to write and read.
If your unique_id is really unique, you don't need LIMIT 1.

Issue with MySQL Concat and like command

I want to validate the data in MYSQL table. Table has 4 fields :
Firstname
Middlename
Lastname
Fullname
I want to compare if CONCAT(firstname, ' ', LASTNAME), matches Fullname
Here is the command I am using :
select * from user_info where CONCAT(firstname, ' ', lastname)
like CONCAT('%', fullname, '%')
However, this is not working. But the following command works :
select * from user_info where CONCAT(firstname, ' ', lastname)
like '%JOHN DOE%'
What could be the issue with the MySQL command ?
Your newly attached data confirms what I suspected, namely that the full name is not necessarily composes simply of the first and last name, but include the middle name, or might even be missing any of the three components. One option here would be to assert that each component present does appear somewhere inside the full name, in the correct order, e.g.
SELECT *
FROM yourTable
WHERE
fullname REGEXP
CONCAT(
CASE WHEN firstname IS NOT NULL
THEN CONCAT('[[:<:]]', COALESCE(firstname, ''), '[[:>:]]')
ELSE '' END,
'.*',
CASE WHEN middlename IS NOT NULL
THEN CONCAT('[[:<:]]', COALESCE(middlename, ''), '[[:>:]]')
ELSE '' END,
'.*',
CASE WHEN lastname IS NOT NULL
THEN CONCAT('[[:<:]]', COALESCE(lastname, ''), '[[:>:]]')
ELSE '' END);
Demo
You need to change order of condition in your code :-
select * from table1 where fullname
like CONCAT('%', trim(CONCAT(firstname,' ',middlename,' ',lastname)) , '%')
SQL Fiddle

Change position of last name and rest of name in MySQL query

My 'name' column has names stored like this
Lastname Firstname Middlename
I want to display it like this in my query:
Firstname Middlename Lastname
Not all records have a middle name, so they may be 1 or 2 spaces in the column
I have tried this :
SELECT CONCAT ( SUBSTRING_INDEX(`name`, ' ', 1) , ' ' , SUBSTRING_INDEX(`name`, ' ', -1) ) AS nicename`
But this only gives the last name. The "-1" part is not working...
Thanks for all help.
To start with, that's a bad design, Now, since your middlename part may be empty, you may bear with it and just select the name saying select name from tbl1.
Else, consider re-designing your table to have separate columns for Lastname, Firstname and Middlename and then You don't need all of this. You can just get data from all 3 columns saying
select concat(Firstname, Middlename, Lastname ) as nicename
from tbl1;
Found a solution :
SELECT concat ( TRIM( SUBSTR(`name`, LOCATE(' ', `name`)) ), ' ', SUBSTRING_INDEX(SUBSTRING_INDEX(`name`, ' ', 1), ' ', -1) ) as nicename
Source: How to split the name string in mysql?

Splitting a single column (name) into two (forename, surname) in SQL

Currently I'm working on a database redesign project. A large bulk of this project is pulling data from the old database and importing it into the new one.
One of the columns in a table from the old database is called 'name'. It contains a forename and a surname all in one field (ugh). The new table has two columns; forenames and surname. I need to come up with a clean, efficient way to split this single column into two.
For now I'd like to do everything in the same table and then I can easily transfer it across.
3 columns:
Name (the forename and surname)
Forename (currently empty, first half of name should go here)
Surname (currently empty, second half of name should go here)
What I need to do: Split name in half and place into forename and surname
If anyone could shed some light on how to do this kind of thing I would really appreciate it as I haven't done anything like this in SQL before.
Database engine: MySQL
Storage engine: InnoDB
A quick solution is to use SUBSTRING_INDEX to get everything at the left of the first space, and everything past the first space:
UPDATE tablename
SET
Forename = SUBSTRING_INDEX(Name, ' ', 1),
Surname = SUBSTRING_INDEX(Name, ' ', -1)
Please see fiddle here. It is not perfect, as a name could have multiple spaces, but it can be a good query to start with and it works for most names.
Try this:
insert into new_table (forename, lastName, ...)
select
substring_index(name, ' ', 1),
substring(name from instr(name, ' ') + 1),
...
from old_table
This assumes the first word is the forename, and the rest the is lastname, which correctly handles multi-word last names like "John De Lacey"
For the people who wants to handle fullname: John -> firstname: John, lastname: null
SELECT
if( INSTR(`name`, ' ')=0,
TRIM(SUBSTRING(`name`, INSTR(`name`, ' ')+1)),
TRIM(SUBSTRING(`name`, 1, INSTR(`name`, ' ')-1)) ) first_name,
if( INSTR(`name`, ' ')=0,
null,
TRIM(SUBSTRING(`name`, INSTR(`name`, ' ')+1)) ) last_name
It works fine with John Doe. However if user just fill in John with no last name, SUBSTRING(name, INSTR(name, ' ')+1)) as lastname will return John instead of null and firstname will be null with SUBSTRING(name, 1, INSTR(name, ' ')-1).
In my case I added if condition check to correctly determine lastname and trim to prevent multiple spaces between them.
This improves upon the answer given, consider entry like this "Jack Smith Smithson", if you need just first and last name, and you want first name to be "Jack Smith" and last name "Smithson", then you need query like this:
-- MySQL
SELECT
SUBSTR(full_name, 1, length(full_name) - length(SUBSTRING_INDEX(full_name, ' ', -1)) - 1) as first_name,
SUBSTRING_INDEX(full_name, ' ', -1) as last_name
FROM yourtable
Just wanted to share my solution. It also works with middle names. The middle name will be added to the first name.
SELECT
TRIM(SUBSTRING(name,1, LENGTH(name)- LENGTH(SUBSTRING_INDEX(name, ' ', -1)))) AS firstname,
SUBSTRING_INDEX(name, ' ', -1) AS lastname
I had a similar problem but with Names containing multiple names, eg. "FirstName MiddleNames LastName" and it should be "MiddleNames" and not "MiddleName".
So I used a combo of substring() and reverse() to solve my problem:
select
SystemUser.Email,
SystemUser.Name,
Substring(SystemUser.Name, 1, instr(SystemUser.Name, ' ')) as 'First Name',
reverse(Substring(reverse(SystemUser.Name), 1, instr(reverse(SystemUser.Name), ' '))) as 'Last Name',
I do not need the "MiddleNames" part and maybe this is not the most efficient way to solve it, but it works for me.
Got here from google, and came up with a slightly different solution that does handle names with more than two parts (up to 5 name parts, as would be created by space character). This sets the last_name column to everything to the right of the 'first name' (first space), it also sets full_name to the first name part. Perhaps backup your DB before running this :-) but here it is it worked for me:
UPDATE users SET
name_last =
CASE
WHEN LENGTH(SUBSTRING_INDEX(full_name, ' ', 1)) = LENGTH(full_name) THEN ''
WHEN LENGTH(SUBSTRING_INDEX(full_name, ' ', 2)) = LENGTH(full_name) THEN SUBSTRING_INDEX(del_name, ' ', -1)
WHEN LENGTH(SUBSTRING_INDEX(full_name, ' ', 3)) = LENGTH(full_name) THEN SUBSTRING_INDEX(del_name, ' ', -2)
WHEN LENGTH(SUBSTRING_INDEX(full_name, ' ', 4)) = LENGTH(full_name) THEN SUBSTRING_INDEX(del_name, ' ', -3)
WHEN LENGTH(SUBSTRING_INDEX(full_name, ' ', 5)) = LENGTH(full_name) THEN SUBSTRING_INDEX(del_name, ' ', -4)
WHEN LENGTH(SUBSTRING_INDEX(full_name, ' ', 6)) = LENGTH(full_name) THEN SUBSTRING_INDEX(del_name, ' ', -5)
ELSE ''
END,
full_name = SUBSTRING_INDEX(full_name, ' ', 1)
WHERE LENGTH(name_last) = 0 or LENGTH(name_last) is null or name_last = ''
SUBSTRING_INDEX didn't work for me in SQL 2018, so I used this:
declare #fullName varchar(50) = 'First Last1 Last2'
declare #first varchar(50)
declare #last varchar(50)
select #last = right(#fullName, len(#fullName)-charindex(' ',#fullName, 1)), #first = left(#fullName, (charindex(' ', #fullName, 1))-1);
Yields #first = 'First', #last = 'Last1 Last2'