I need to gather data from two columns, concat them so that it's only the first six of the first column and the last six of the second column, separated by ' + '. Some have been input with weird spaces in front or in back, so we must also use the trim feature and get rid of all NULL. I haven't had any issues with the first part, but am struggling to use the trim feature in a way that gives the desired output.
Output needs to look like this:
Input Data sample:
The following code returns results, but the output doesn't match so I know the trim is wrong:
SELECT CONCAT(SUBSTRING(baseball, 1, 6), ' + ',
SUBSTRING(football, -6)) AS MYSTRING
FROM datenumtest2
WHERE baseball IS NOT NULL AND football IS NOT NULL;
I also tried the following, but get an error message about the parameters being incorrect:
SELECT CONCAT(SUBSTRING(LTRIM(baseball, 1, 6)), ' + ',
SUBSTRING(RTRIM(football, -6))) AS MYSTRING
FROM datenumtest2
WHERE baseball IS NOT NULL AND
football IS NOT NULL;
I'm still new to this site and learning, but I have tried to include as much as I can! If there is other information that I can add to help, please let me know.
You just need to use Trim() on the column(s), before using Substring() function on them:
SELECT CONCAT(SUBSTRING(TRIM(baseball), 1, 6), ' + ',
SUBSTRING(TRIM(football), -6)) AS MYSTRING
FROM datenumtest2
WHERE baseball IS NOT NULL AND
football IS NOT NULL;
Related
Imagine I have a table which has a Params column and it contains settings of my gallery. I want to add 2 other properties automatically with MySQL query.
I have already test this query but it will add my new properties at the first of the column value which is incorrect :
UPDATE table
SET params=CONCAT(', "slider_fullscreen_button_skin": "myTheme", "slider_zoompanel_skin": "myTheme"',params)
WHERE params NOT LIKE '%myTheme%';
let's say I have this value on my column :
{"title":"Bessariabian","alias":"Bessariabian","category":"1103","full_width":"false"}
I want my value change to something like this:
{"title":"Bessariabian","alias":"Bessariabian","category":"1103","full_width":"false", "slider_fullscreen_button_skin": "myTheme", "slider_zoompanel_skin": "myTheme"}
I want to make a query which adds the new properties at the end of the value before } location.
How I can handle this?
Use Substring_Index() function to get the Substring before the first occurence of }.
Now, Concat() this substring with your required string, and } at the end.
Try:
UPDATE table
SET params = CONCAT(
SUBSTRING_INDEX(params, '}', 1),
', "slider_fullscreen_button_skin": "myTheme", "slider_zoompanel_skin": "myTheme"',
'}'
)
WHERE params NOT LIKE '%myTheme%';
I have 4 types of last_name:
"Camp Bell"
"CAMPBELL"
"CampBellJr."
"camp bell jr."
Now, in rails when an user is searched by it's last name like camp bell, I want to show all the 4 records. So, I tried:
RAILS
stripped_name = params[last_name].gsub(/\W/, '')
#=> "campbell"
User.where("LOWER(REPLACE(last_name, '/\W/', '')) LIKE ?", "#{stripped_name}%")
Give me only 2 records with following last_name:
"CAMPBELL"
"CampBellJr."
I guess, this is because, the mysql REPLACE is not working correctly with regex.
Any ideas?
EDIT
Guys, sorry for the confusion. My idea is to strip off all special characters including space. So I'm trying to use \W regex.
For example, the input can be: camp~bell... But, it should still fetch result.
You can check for both stripped_name without space and ones that include both names seperated with space like this.
stripped_name = params[last_name].gsub(/\W/, '')
split_names = params[last_name].split(" ")
User.where('name LIKE ? OR (name LIKE ? AND name LIKE ?)', "%#{stripped_name}%", "%#{split_names[0]}%", "%#{split_names[1]}%")
Next step would to search for complete array of split names not just first two.
Here my solution:
User.where("REPLACE(last_name, ' ', '') ILIKE CONCAT ('%', REPLACE('?', ' ', ''),'%')", stripped_name)
ILIKE is like LIKE but the I is for insensitive case.
To understand easily step by step:
lastname ILIKE '%campbell% you need % because you want lastname
contain this string, not necessary at the begin or the end of you
string.
'campbell%' => search string who begin by campbell
'%campbell' => search string who finish by campbell
We need generate '%campbell%, so we use CONCAT for that
I just use a simply REPLACE, but maybe you should use a regex.
My table has a column with a JSON string that has nested objects (so a simple REPLACE function cannot solve this problem) . For example like this: {'name':'bob', 'blob': {'foo':'bar'}, 'age': 12}. What is the easiest query to append a value to the end of the JSON string? So for the example, I want the end result to look like this: {'name':'bob', 'blob': {'foo':'bar'}, 'age': 12, 'gender': 'male'} The solution should be generic enough to work for any JSON values.
What about this
UPDATE table SET table_field1 = CONCAT(table_field1,' This will be added.');
EDIT:
I personally would have done the manipulation with a language like PHP before inserting it. Much easier. Anyway, Ok is this what you want? This should work providing your json format that is being added is in the format {'key':'value'}
UPDATE table
SET col = CONCAT_WS(",", SUBSTRING(col, 1, CHAR_LENGTH(col) - 1),SUBSTRING('newjson', 2));
I think you can use REPLACE function to achieve this
UPDATE table
SET column = REPLACE(column, '{\'name\':\'bob\', \'blob\': {\'foo\':\'bar\'}, \'age\': 12}', '{\'name\':\'bob\', \'blob\': {\'foo\':\'bar\'}, \'age\': 12, \'gender\': \'male\'}')
Take care to properly escape all quotes inside json
Upon you request of nested json, i think you can just remove last character of the string with SUBSTRING function and then append whatever you need with CONCAT
UPDATE table
SET column = CONCAT(SUBSTRING(column, 0, -1), 'newjsontoappend')
modify Jack's answer. Works perfectly even column value is empty on first update.
update table
set column_name = case when column_name is null or column_name =''
then "{'foo':'bar'}"
else CONCAT_WS(",", SUBSTRING(column_name, 1, CHAR_LENGTH(column_name) - 1),SUBSTRING("{'foo':'bar'}", 2))
end
I would like to split a string like this in Access 2000 (Visual Basic function):
"[Results]
[Comments]"
in two parts:
the results part
the comments part
As you can notice, these two parts are separated by an empty line (always, this is our separator).
[Results] and [Comments] are blocks of text. We don't care what's in it except:
the results part doesn't have any empty lines in it, so the first empty line we see is the separator one.
I want my function to extract the Comments part only.
Here is what i tried:
Public Function ExtractComm(txt As String) As String
Dim emptyLine As Integer
txt = Trim(txt)
'emptyLine = first empty line index ??
emptyLine = InStrRev(txt, (Chr(13) + Chr(10)) & (Chr(13) + Chr(10)))
'Comments part = all that is after the empty line ??
ExtractComm = Mid(txt, emptyLine + 4)
End Function
But it doesn't work well.
If I do:
ExtractComm(
"Res1
Res2
Comment1
Comment2"
)
I want to obtain:
"Comment1
Comment2"
but I only obtain Comment2. Any idea to extract the comment part ?
Thanks a lot !
Maybe you need to use InStr instead of InStrRev
InStrRev
Returns the position of the first occurrence of one string within another, starting from the right side of the string.
InStr
Returns an integer specifying the start position of the first occurrence of one string within another.
I am having issues with a particular like in my active records query.
When I use join('users parent', 'child.treePath LIKE CONCAT(parent.treePath,"%")')
Code igniter spits out JOIN 'users' parent ON 'child'.'treePath' 'LIKE' CONCAT(parent.treePath,"%") (note that I have replaced all back ticks (`) with (') due to markdown :/)
So, the issue is that code igniter is wrapping LIKE in (`).
How can I tell it to not attempt to format this block?
Complete query:
$this->db->select('child.uuid')
->from('users child')
->join('users parent', 'child.treePath LIKE CONCAT(parent.treePath,"%")')
->where('parent.uuid', $uuid)
->where("LENGTH(REPLACE(child.treePath, parent.treePath, '')) - LENGTH(REPLACE(REPLACE(child.treePath, parent.treePath, ''), '/', '')) <= ", $levels, 'false')
->where("LENGTH(REPLACE(child.treePath, parent.treePath, '')) - LENGTH(REPLACE(REPLACE(child.treePath, parent.treePath, ''), '/', '')) > ", 0, 'false')
->group_by('child.treeId');
If you are chaining all these functions together in a single call, you might as well just use
$this->db->query("Write all your specific SQL here");
Not seeing the benefit of wrestling with Codeigniter's query builder in your case.