I am trying to build some address data from a number of different tables and come up with two returned datasets using a UNION query to remove duplicates. I am building the following SQL statement in PHP
$query = "
SELECT
l.UPRN,
(CONCAT(IF(o.ORGANISATION IS NULL, '', CONCAT(o.ORGANISATION, ' ')),
IF(l.SAO_TEXT IS NULL, '', CONCAT(l.SAO_TEXT, ' ')),
IF(l.SAO_START_NUMBER <> 0, SAO_START_NUMBER, ''),
IF(l.SAO_START_SUFFIX IS NULL, '', SAO_START_SUFFIX),
IF(l.SAO_END_NUMBER <> 0, CONCAT('-', SAO_END_NUMBER), ''),
IF(l.SAO_END_SUFFIX IS NULL, '', l.SAO_END_SUFFIX),
IF(l.PAO_TEXT IS NULL, '', CONCAT(' ', l.PAO_TEXT, ' ')),
IF(l.PAO_START_NUMBER <> 0, PAO_START_NUMBER, ''),
IF(l.PAO_START_SUFFIX IS NULL, '', PAO_START_SUFFIX),
IF(l.PAO_END_NUMBER <> 0, CONCAT('-', PAO_END_NUMBER), ''),
IF(l.PAO_END_SUFFIX IS NULL, '', l.PAO_END_SUFFIX),
IF(s.STREET_DESCRIPTION IS NULL, '',
CONCAT(' ', s.STREET_DESCRIPTION, ' ')),
IF(s.LOCALITY_NAME IS NULL, '', CONCAT(s.LOCALITY_NAME, ' ')),
IF(s.TOWN_NAME IS NULL, '', CONCAT(s.TOWN_NAME, ' ')),
IF(s.ADMINISTRATIVE_AREA IS NULL, '',
CONCAT(s.ADMINISTRATIVE_AREA, ' ')),
b.postcode_locator)
) AS single_address_label
FROM addbaseprem.abp_lpi l
INNER JOIN addbaseprem.abp_blpu b
ON b.UPRN = l.UPRN
INNER JOIN addbaseprem.abp_street_descriptor s
ON s.USRN = l.USRN
LEFT JOIN addbaseprem.abp_organisation o
ON o.UPRN = l.UPRN
WHERE l.LOGICAL_STATUS = 1
";
It is working pretty well in that I am getting my UPRN and single_address_label columns returned. I'm having a problem with the following part though
IF(s.ADMINISTRATIVE_AREA IS NULL,'',CONCAT(s.ADMINISTRATIVE_AREA,' ')),
What I would like to happen is not to CONCAT the ADMINISTRATIVE_AREA value if it is the same as the TOWN_NAME value eg i would like something like
IF(s.ADMINISTRATIVE_AREA IS NULL,'',IF((s.ADMINISTRATIVE_AREA == s.TOWN_NAME),'',CONCAT(s.ADMINISTRATIVE_AREA,' ')),
I have tried a few variations of OR != and so on but to no avail - I can't seem to get the code right and keep getting a syntax error. I don't know if I'm trying to do something that's just not possible or just making a schoolboy mistake. It's taken quite a time to get this far...
All help or advice gratefully received.
Try:
IF(s.ADMINISTRATIVE_AREA IS NULL OR s.ADMINISTRATIVE_AREA = s.TOWN_NAME,'',CONCAT(s.ADMINISTRATIVE_AREA,' '))
You can also simplify many of the pieces by using IFNULL:
IFNULL(column, '')
is equivalent to:
IF(column IS NULL, '', column)
Related
I would like to replace data in column RANDOM that equal to '0', NULL, 'NONE', 'NA' WITH 'N/A'.
I used nested REPLACE as below:
SELECT IDNO,
REPLACE (
REPLACE (
REPLACE(
REPLACE(RANDOM, 'NONE|NA', 'N/A'),
'0','N/A'),
'-',''),
NULL, 'N/A') AS NUMBER
FROM TABLE1
It does replace data '0' with 'N/A'. However, it does replace other data that contain 0 in that too. Example: 04110 change to N/A411N/A
I want to replace the one that exactly have value '0' only.
SELECT IDNO,
REPLACE (
REPLACE (
REPLACE(
REPLACE(RANDOM, 'NONE|NA', 'N/A'),
'/0','N/A'),
'-',''),
NULL, 'N/A') AS NUMBER
FROM TABLE1
When I do this (add \ in front of 0) it does not change any of the 0 to 'N/A'
How do I replace data with the exact value '0' with 'N/A' then?
Thank you in advance. :)
... RANDOM that equal to '0', NULL, 'NONE', 'NA' WITH 'N/A'
"Equal" means that there's nothing else in that column. In that case, use CASE:
select idno,
case when random in ('0', 'NONE', 'NA') or radnom is NULL then 'N/A'
else random
end as result
from table1
Hint: Check out IF function of your sql server. Try this:
SELECT
IDNO,
IF(Random IS NULL or Random = '0' or Random='NONE' or Random = 'NA', 'N/A', Random)
FROM
TABLE1
I have a table in MySQL like below,
Now I want to get an output like below,
id |username |accessLevel
============================
6 |deepaku8 |arch[ALL]
7 |kirajama |arch[ALL]- geo[APJ]
8 |asau |arch[Data Center]- geo[EMEAR_REGION]
Is there any way to achieve this result by SQL query ?
This does the basics for you table (guessing the columns you want)
SELECT id,
username,
CONCAT_WS(' - ',
IF(arch IS NULL OR arch = '', NULL, CONCAT('arch', '[', arch, ']')),
IF(geo IS NULL OR geo = '', NULL, CONCAT('geo', '[', geo, ']')),
IF(theater IS NULL OR theater = '', NULL, CONCAT('theater', '[', theater, ']')),
IF(operation IS NULL OR operation = '', NULL, CONCAT('operation', '[', operation, ']')),
IF(region IS NULL OR region = '', NULL, CONCAT('region', '[', region, ']')),
IF(country IS NULL OR country = '', NULL, CONCAT('country', '[', country, ']')),
IF(technology IS NULL OR technology = '', NULL, CONCAT('technology', '[', technology, ']')),
IF(subTechnology IS NULL OR subTechnology = '', NULL, CONCAT('subTechnology', '[', subTechnology, ']'))
) AS accessLevel
FROM some_table
You query in SQL using the SELECT statement. SQL commands are implemented as SQL command strings. Here is a good tutorial by Microsoft.
You can use concat_ws to do this.
concat returns null if any of the values is null and concat_ws ignores null values during concatenation.
select id,username,
concat_ws('-',concat('arch','[',if(arch='',null,arch),']'),
concat('geo','[',if(geo='',null,geo),']'),
concat('technology','[',if(technology='',null,technology),']')
--add more values as required
)
from tablename
I want to update my record on certain conditions.
eg. I've a column ResidenceAddress1, which has email id along with the address.
Sample data:
sap3200#gmail.com,Rourkela
sap3212#gmail.com 2nd street,7 hills
2nd street, sap3212#gmail.com
I am finding the email from ResidenceAddress1 this way:
select (concat(trim(substring_index(substring_index(Residence_Address1, '#', '1'), ' ', -1)),'','#gmail.com') as mail,Residence_Address1
from mytable
where Residence_Address1 like '%gmail%' and Email_Personal1=""
When I update it this way:
update mytable
set email_Personal1=concat(trim(substring_index(substring_index(Residence_Address1, '#', '1'), ' ', -1)), '','#gmail.com') ,
Residence_Address1=replace(residence_address1,"'concat(trim(substring_index(substring_index(Residence_Address1, '#', '1'), ' ', -1)), '','#gmail.com')'",'')
where Residence_Address1 like '%gmail%' and Email_Personal1=""
This way, it updates email_personal1 but didn't update residence_address1 with replaced empty value instead of gmail id value in that row. Where am I mistaking here?
You can update multiple columns and mix string functions in an update. In the question, you have extra double quotes, which are not needed. Perhaps you intend something like this:
update fulldata_table
set email_Personal1 = concat(trim(substring_index(substring_index(Residence_Address1, '#', '1'
), ' ', -1)
), '', '#gmail.com'),
Residence_Address1 = replace(residence_address1, concat(trim(substring_index(substring_index(Residence_Address1, '#', '1'), ' ', -1)), '', '#gmail.com', '')
where Residence_Address1 like '%gmail%' and Email_Personal1 = ''
Try this:
UPDATE fulldata_table SET
email_Personal1 = concat(trim(substring_index(substring_index(Residence_Address1, '#', '1'),' ',-1 ) ), '#gmail.com') ,
Residence_Address1 = replace( residence_address1, concat( trim( substring_index( substring_index(Residence_Address1, '#', '1'), ' ', -1 ) ), '#gmail.com', '' ), '' )
WHERE Residence_Address1 LIKE '%gmail%' AND Email_Personal1 = '';
This is the query i execute after insertation in some table in my database. Here i am getting rate_like_id and all other fields i also save them but when i use CONCAT and trying to save them as json it inserts NULL value via trigger.
Is this a wrong way to do this. Is ther any other way i can save this type of data via trigger mysql.
INSERT INTO `log_activity`(`visitor_id`,
`rating_like_id`,
`type`,
`response`,
`created_by`,
`created_date`)
VALUES (new.created_by,
new.rating_like_id,
CASE WHEN new.is_like = NULL THEN "Rating" ELSE "Like" END ,
-- Here is this column Should not be null but it is coming null when INSERTED
CONCAT(
'{"card_id":','"',new.card_id,'"',
',"card_type":','"',new.card_type,'"',
',"user_id":','"',new.user_id,'"',
',"is_like":','"',new.is_like,'"',
',"has_rated":','"',new.has_rated,'"',
',"rate":','"',new.rate,'"',
',"created_by":','"',new.created_by,'"',
',"created_date":','"',new.created_date,'"',
',"card_type":','"',new.card_type,'"','}'),
new.created_by,
new.created_date)
what is wrong with this .. all other fields are saved correctly only CONCAT field is not getting inserted properly.
Yes I am able to insert value like this
CONCAT(" hi "," how "," are "," you ", " ? ")
Is this problem because i am using "new.fieldName" inside CONCAT ... i see THIS question they are doing the same thing .. ofcource it is less complex compare to mine.
If you see comments and conversation between me and marcB.. you will get the answer...
Here i want to show what changes i made to my query to make it work.
marcB said :- Remember that sql null is contagious. if ANY of the fields you're concatting are themselves null, the ENTIRE result becomes null
so you can see my query in question.. i do not have checked for any value is it null or not. So i just had to add the null check.
INSERT INTO `log_activity`(`visitor_id`,
`rating_like_id`,
`type`,
`response`,
`created_by`,
`created_date`)
VALUES (new.created_by,
new.rating_like_id,
CASE WHEN new.is_like = NULL THEN "Rating" ELSE "Like" END,
CONCAT('{"card_id":',
'"',
IFNULL(new.card_id, ''),
'"',
',"card_type":',
'"',
IFNULL(new.card_type, ''),
'"',
',"user_id":',
'"',
IFNULL(new.user_id, ''),
'"',
',"is_like":',
'"',
IFNULL(new.is_like, ''),
'"',
',"has_rated":',
'"',
IFNULL(new.has_rated, ''),
'"',
',"rate":',
'"',
IFNULL(new.rate, ''),
'"',
',"created_by":',
'"',
IFNULL(new.created_by, ''),
'"',
',"created_date":',
'"',
IFNULL(new.created_date, ''),
'"',
',"card_type":',
'"',
IFNULL(new.card_type, ''),
'"',
'}'),
new.created_by,
new.created_date)
It checks for the null value of the field.
In the below piece of code, I am creating an Address field by concatenating various parts of an address.
However, if for instance address2 was empty, the trailing , will still be concatenated into Address.
This means if all fields were empty, I end up with a result of ,,,,.
If address1 is "House Number" and everything else is empty, I end up with House Number,,,,.
CONCAT( COALESCE(address1,'') , ', ' ,
COALESCE(address2,'') , ', ' ,
COALESCE(address3,'') , ', ' ,
COALESCE(city,'') , ', ' ,
COALESCE(zip, '')
) AS Address,
Is there some way of conditionally placing the commas between address parts only if the content of an address part is not empty.
Such as something along the lines of (pseudo-code) IF(address1) is NULL use '' ELSE use ','
Thank you.
CONCAT_WS(', ',
IF(LENGTH(`address1`),`address1`,NULL),
IF(LENGTH(`address2`),`address2`,NULL),
IF(LENGTH(`address3`),`address3`,NULL),
IF(LENGTH(`city`),`city`,NULL),
IF(LENGTH(`zip`),`zip`,NULL)
)
Using CONCAT_WS as Mat says is a very good idea, but I thought I'd do it a different way, with messy IF() statements:
CONCAT( COALESCE(address1,''), IF(LENGTH(address1), ', ', ''),
COALESCE(address2,''), IF(LENGTH(address2), ', ', ''),
COALESCE(address3,''), IF(LENGTH(address3), ', ', ''),
COALESCE(city,''), IF(LENGTH(city), ', ', ''),
COALESCE(zip,''), IF(LENGTH(address1), ', ', ''),
) AS Address,
The IF()s check if the field has a length and if so returns a comma. Otherwise, it returns an empty string.
try with MAKE_SET
SELECT MAKE_SET(11111,`address1`,`address2`,`address3`,`city`,`zip`) AS Address
It will returns a string with all NOT NULL value separated by ,
CONCAT_WS(', ',
NULLIF(`address1`,''),
NULLIF(`address2`,''),
NULLIF(`address3`,''),
NULLIF(`city`,''),
NULLIF(`zip`,'')
)
CONCAT_WS combines non-NULL strings.
NULLIF writes NULL if left and right side are equals. In this case if values are equals an empty sting ''.