I need to extract everything after the last '=' (http://www.domain.com?query=blablabla - > blablabla) but this query returns the entire strings. Where did I go wrong in here:
SELECT RIGHT(supplier_reference, CHAR_LENGTH(supplier_reference) - SUBSTRING('=', supplier_reference))
FROM ps_product
select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;
Please use this for further reference.
Try this (it should work if there are multiple '=' characters in the string):
SELECT RIGHT(supplier_reference, (CHARINDEX('=',REVERSE(supplier_reference),0))-1) FROM ps_product
Try this in MySQL.
right(field,((CHAR_LENGTH(field))-(InStr(field,','))))
In MySQL, this works if there are multiple '=' characters in the string
SUBSTRING(supplier_reference FROM (LOCATE('=',supplier_reference)+1))
It returns the substring after(+1) having found the the first =
If your string is
str = 'abc=def=ghi'
To select to the right:
select substring_index(str,'=',-1) from tablename ==> result is 'ghi'
select substring_index(str,'=',-2) from tablename ==> result is 'def=ghi'
To select to the left
select substring_index(str,'=',-1) from tablename ==> result is 'abc'
select substring_index(str,'=',2) from tablename ==> result is 'abc=def'
I've been working on something similar and after a few tries and fails came up with this:
Example:
STRING-TO-TEST-ON = 'ab,cd,ef,gh'
I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".
My query is:
SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`
Now let me try and explain what I did ...
I had to find the position of the last "," from the string and to calculate the wantedString length, using LOCATE(",",REVERSE('ab,cd,ef,gh'))-1 by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".
calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:
LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1
I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.
all it remain to do is running a SUBSTR on my initial string FROM the calculated position.
I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.
For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:
CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END
SELECT NULLIF(SUBSTRING_INDEX(column, '=', -1), column)
Related
How would I go about extracting a SUNSTRING IF a commas exists or just returning the whole string if no commas was found?
For example:
640 => 640
310,321,450 => 310
1024,5,78, 900 => 1024
I was thinking of doing something like this: (suppose this string is in a table row called author_ids )
[...]
WHERE SUBSTR(a.author_ids, 0, INSTR(a.author_ids, ',')) = b.author_id
OR a.author_ids = b.author_id
[...]
But this is clearly not working.
Thanks.
Additional information:
There are about 10% of the "author_ids" that have more than one author, so a.author_ids = b.author_id works correctly but has "" or null when there are more than one author.
Here are two methods:
select substring_index(val, ',', 1)
or
select val + 0
The first gets everything before the first comma. The second converts the string to a number. All characters after and including the first non-numeric character (such as ',') are ignored.
It would seem that you are storing lists of numbers in a comma-delimited string. This is a bad idea. You should probably consider using a junction table instead of storing numbers as strings and lists in a string and not a table.
SELECT CASE
WHEN author_ids LIKE '%,%'
THEN SUBSTRING_INDEX(author_ids, ',', 1)
ELSE author_ids
END AS author_ids
FROM yourtable
SQL FIDDLE: http://sqlfiddle.com/#!9/fca0e/3/0
I'm trying to change a table field that contains decimal numbers from varchar(255) to decimal(12,2). And before I do that, I'd like to find out if there is information that would get deleted in the process: are there any rows where this field contains something other than a decimal(12,2).
I'm stumped how to do this. Apparently there isn't a string function like is_numeric() in PHP. I already tried casting the field to decimal and then comparing it with the original string, but this returns TRUE even for obvious cases where it should not:
select ('abc' = convert('abc', decimal(12,2)));
returns 1
Any help? How do I find out if a string contains something other than a decimal in MySQL? Thanks.
Stupid me, I have to cast twice (to decimal and back to char), which makes it work:
select ('abc' = convert(convert('abc', decimal(12,2)), char(255)));
returns 0
Thanks.
If you want to examine if the strings are actually floating points numbers, you could also use a regular expression. The following regex can help :)
SELECT '31.23' REGEXP '^[[:digit:]]+([.period.][[:digit:]]+)?$'; # returns 1
SELECT '31' REGEXP '^[[:digit:]]+([.period.][[:digit:]]+)?$'; # returns 1
SELECT 'hey' REGEXP '^[[:digit:]]+([.period.][[:digit:]]+)?$'; # returns 0
From select statement, in a filed I want to remove last characters is character if its number. Is there string function available in MySQL?
for these two SQL I want
test
as output
select 'test1';
select 'test';
Another way is to use REGEXP,
SET #val = 'test12';
SELECT CONCAT(LEFT(#val, CHAR_LENGTH(#val) - 1),
IF(RIGHT(#val, 1) REGEXP '[0-9]' = 0, RIGHT(#val, 1), ''))
SQLFiddle Demo
SQLFiddle Demo (another example)
To remove the last character if it's numeric, one way to do this without using a regular expression is with LEFT, RIGHT and LENGTH :
select if( right(yourfield,1) = 0 && right(yourfield,1) != '0',
yourfield,
left(yourfield, length(yourfield) - 1))
from yourtable;
To replace all trailing numeric values, you can use REVERSE:
select if( cast(reverse(yourfield) as signed) = 0 && right(yourfield,1) != '0',
yourfield,
left(yourfield, length(yourfield) - length((reverse(yourfield) + 0))))
from yourtable;
SQL Fiddle Demo
When casting fields as integers/signed in MySQL, it will cast all the numeric characters up to the first non-numeric character -- thus making the REVERSE work. If the last character is not numeric, it results in 0.
Using the IF check above, if the last character isn't numeric, then it prints the original value, else it prints all but the last character.
here is a pointer:
use a union between two queries.
in the first - either use REGEX, or grab the substr of the field where another substr for the last char is a number,
then union the text field where the substr of the last char is not a number.
You might want to use Regular Expressions inside MySQL. This package might help you https://launchpad.net/mysql-udf-regexp. However, I do not recommend to do it inside MySQL statement as it might be slow. You would better to do it after grabbing the value inside your programming language.
I am using the following to only select the first 40 characters from a column
SELECT SUBSTRING(w.item_title,1,40) as title from tableName blah blah
What I really want to do though is:
If w.item_title is over 40 characters, return only the first 40 and append with ... else just return w.item_title as it is
Is this possible at SELECT stage and should it be done there? Or should it be processed after the fact?
I am using JS to display the results.
SELECT SUBSTR(INSERT(w.item_title, 41, 3, '...'), 1, 43)
FROM ...
See the manual on the INSERT() String function for examples.
INSERT(str,pos,len,newstr)
Returns the string str, with the substring beginning at position pos
and len characters long replaced by the string newstr. Returns the
original string if pos is not within the length of the string.
Replaces the rest of the string from position pos if len is not within
the length of the rest of the string. Returns NULL if any argument is
NULL.
EDIT
Last parameter of SUBSTR should be 43 as pointed out by Joachim.
QUERY:
SELECT CASE WHEN LENGTH(w.item_title)>40
THEN SUBSTRING(w.item_title,1,40)
ELSE w.item_title END as title
from tableName w
You can just use an 'IF' to append your suffix;
SELECT CONCAT(SUBSTRING(w.item_title,1,40),
IF(LENGTH(w.item_title)>40, '...', '')) as title
FROM tableName w
SQLfiddle demo here.
On whether it should be done in the database, that's a trickier question that can as always be answered with "it depends".
If your text is long (for example articles), it's rather clear cut that you don't want to transfer the whole article if you only need the first 40 characters, but if the texts are short, you may want to offload the calculation from the database. It's easy to add web servers, but scaling the database up is expensive.
You can also try with Left
SELECT CONCAT(Left(w.item_title,40),
IF(LENGTH(w.item_title)>40, 'something', '')) as title
FROM tableName w
;
Another:
SELECT case when Length(w.item_title) > 40 then
Left(w.item_title,40) else
CONCAT(coalesce(w.item_title,''), 'something') End as title
FROM tableName w
;
I may end up having to do this with my PHP on the result set, but I was hoping the DB could do this for me. I'm wanting to check a field and if it matches a condition, set another field equal to another field + a string. Here's my attempts:
SELECT CASE UnityReq WHEN '1' THEN Table + ' (Unity)' ELSE Table END AS Type
If the Table were equal to Event, I'd want to get 'Event (Unity)' as Type.
I saw in a different post you have to cast your field if combining with a string, so I tried this:
SELECT CASE WHEN UnityReq = 1 THEN CAST(Table AS NVARCHAR(200)) + ' (Unity)' ELSE Table END AS Type
And tried the MySQL CONCAT function:
SELECT CASE UnityReq WHEN 1 THEN CONCAT(Table, ' (Unity)') ELSE Table END AS Type
I've also tried both WHEN's with or without the quotes around the number (as it's an INT field), and about every format I've been able to find googling for CASE, but I'm always getting SQL syntax errors. I feel like I've tried every version of this command I can come up with but I'm not having any luck. Any pointers?
It's not CASTing you're after, but CONCATenation.
Something like:
SELECT
CASE WHEN UnityReq = 1 THEN CONCAT(Table, ' (Unity)') ELSE Table END AS Type
FROM ...