Run MySQL Query if condition is true else run another query - mysql

I need to split address column into streetName and streetNumber. The problem is sometimes the complete address in located in the streetName column , and sometimes too inside the streetNumber column. I am using this code to do the splitting
replace(streetName, substring_index(streetName, ' ', -1), '') as
street,substring_index(streetName, ' ', -1) as number
and
replace(streetNumber, substring_index(streetNumber, ' ', -1), '') as
street,substring_index(streetNumber, ' ', -1) as number.
What I want to do is run this section of my select query statement if streetName is null or empty execute the code with the streetNumber and vice versa.
I have to sections ifStreet() and IfStreetNumber() in a stored Procedure. But I get an error when I run it , and If I put the code directly inside the case statements it does not work as well.I get an error message, You have an error in your SQL Syntax. Is it possible to run a query base on condition or what is wrong with my approach? Thank you,
SELECT
firstName,
lastName,
D.email AS email,
streetName,
streetNumber,
zipCode,
city,
IF(length(zipCode) =5,'Germany','') As country,
registeredOn,
N.email AS matchedEmail,
CASE
WHEN gender = 'Frau' OR gender = 'f' THEN 'f'
WHEN gender = 'Herr' OR gender = 'm' THEN 'm'
ELSE ''
END AS Title,
CASE
WHEN gender = 'Frau' OR gender = 'f' THEN 'Frau'
WHEN gender = 'Herr' OR gender = 'm' THEN 'Herr'
ELSE ''
END AS Salutation,
CASE
WHEN streetName !='' THEN
call ifStreet()
ELSE
call ifStreetNumber()
END
FROM
matchFiles.TableA AS D
INNER JOIN
matchFiles.TableB AS N ON D.email = N.email
WHERE
registeredOn <= '2018-08-31';

Stored Procedures are not allowed within SELECT Statements. So your approach will not work.
Try to shift your logic from your stored procedure into adequate subquery.

I restructured the query and also dropped using a stored procedure . I using an IFNULL function to do the alternation to use either streetName or streetNumber depending on which column has a the full address string.
replace(IFNULL(streetName,streetNumber), substring_index(IFNULL(streetName,streetNumber), ' ', -1), '') as street,substring_index(IFNULL(streetName,streetNumber), ' ', -1) as number

Related

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

MysQL Update if a count condition is met

I have a table which consists of 5000 rows. I need SQL command that could update each row by removing all values in "(...)" if only one couple of () is found.
Basically, if I have a name in a row:
Name surname (extra info)
I need to remove "(extra info)" and leave only Name surname
But if there is no additional couple of ()
If there is a row
Name Surname(data) (extra info)
The script should not amend this name
In simple words, I need to update a name where is only one ( or ) symbol
Many thanks
can you try to find first '(' and substring to it ?
don't forget to use case for none ( in string
update userlogin
set fullname = case position('(' in FullName)
when 0
then fullname
else substring(Fullname,1,position('(' in FullName) - 1)
end
This is an implementation of my question. I used select to let me check the result before applying it to update request. The script shows a table of
3 columns: Id, Name, UpdatedName, where Name is what we have and UpdatedName what we will obtain
SELECT `Id`,`Name`,
(case when ((LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1)
THEN
SUBSTRING_INDEX(`Name`, '(', 1)
ELSE
'-'
END)
as updated_name,
FROM table
WHERE (LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1
LIMIT 0,1500
P.S. I used Id to allow me to amend values
SELECT CASE
WHEN fname = 'correct' THEN 'your condition'
WHEN sname = 'correct' THEN 'your second condition'
ELSE 'baz'
END AS fullname
FROM `databasetable`
or you can do as like also
CASE
WHEN action = 'update' THEN
UPDATE sometable SET column = value WHERE condition;
WHEN action = 'create' THEN
INSERT INTO sometable (column) VALUES (value);
END CASE

CASE WHEN does not exist on Access SQL

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?

Incorrect parameter count in the call to native function 'ISNULL'

I have a query that I am trying to convert to MySQL from MS SQL Server 2008. It runs fine on MSSQL,
I get the error
"Incorrect parameter count in the call to native function 'ISNULL'".
How do I solve this?
SELECT DISTINCT
dbo.`#EIM_PROCESS_DATA`.U_Tax_year,
dbo.`#EIM_PROCESS_DATA`.U_Employee_ID,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS033' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS PAYE,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS014' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS TOTALTAXABLE,
dbo.OADM.CompnyName,
dbo.OADM.CompnyAddr,
dbo.OADM.TaxIdNum,
dbo.OHEM.lastName + ', ' + ISNULL(dbo.OHEM.middleName, '') + '' + ISNULL(dbo.OHEM.firstName, '') AS EmployeeName
FROM
dbo.`#EIM_PROCESS_DATA`
INNER JOIN
dbo.OHEM ON dbo.`#EIM_PROCESS_DATA`.U_Employee_ID = dbo.OHEM.empID
CROSS JOIN
dbo.OADM
GROUP BY dbo.`#EIM_PROCESS_DATA`.U_Tax_year , dbo.`#EIM_PROCESS_DATA`.U_Employee_ID , dbo.OADM.CompnyName , dbo.OADM.CompnyAddr , dbo.OADM.TaxIdNum , dbo.OHEM.lastName , dbo.OHEM.firstName , dbo.OHEM.middleName , dbo.`#EIM_PROCESS_DATA`.U_PD_code
MySQL
SELECT DISTINCT
processdata.taxYear, processdata.empID,
CASE WHEN processdata.edCode = 'SYS033' THEN SUM (processdata.amount) END AS PAYE,
CASE WHEN processdata.edCode = 'SYS014' THEN SUM (processdata.amount) END AS TOTALTAXABLE,
company.companyName, company.streetAddress, company.companyPIN, employeemaster.lastName + ', ' + IFNULL(employeemaster.middleName, '')
+ ' ' + IFNULL(employeemaster.firstName, '') AS EmployeeName
FROM
processdata INNER JOIN
employeemaster ON processdata.empID = employeemaster.empID
CROSS JOIN company
GROUP BY processdata.taxYear, processdata.empID, company.companyName, company.streetAddress, company.companyPIN,
employeemaster.lastName, employeemaster.firstName, employeemaster.middleName, processdata.edCode
The MySQL equivalent of ISNULL is IFNULL
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns
expr2.
Maybe also look at SQL NULL Functions
The ISNULL from MySQL is used to check if a value is null
If expr is NULL, ISNULL() returns 1, otherwise it returns 0.
I would suggest that you switch to the ANSI standard function coalesce():
(dbo.OHEM.lastName + ', ' + coalesce(dbo.OHEM.middleName, '') + '' + coalesce(dbo.OHEM.firstName, '')
) AS EmployeeName
You could also make your query easier to read by including table aliases.
EDIT:
As a note, I seemed to have missed the direction of conversion. The MySQL query would use concat():
CONCAT(OHEM.lastName, ', ', coalesce(OHEM.middleName, ''),
coalesce(concat(' ', OHEM.firstName), '')
) AS EmployeeName
I was getting an error when running JUnit tests against a query which had ISNULL(value) with the error saying ISNULL needed two parameters. I fixed this by changing the query to have value is null and the code works the same while the tests now work.