Passing variable into mysql 8 select statement - mysql

I am trying a simple select statement with a variable. The statement works fine if I change the like concat_ws('%', #S, '%'); to a string. It seems that the select statement is not picking up the SET variable. Help would be much appreciated. I am using Mysql80 workbench.
SET #S = "product";
SELECT distinct idproducts FROM mgjtest.vorutaflamedsamheit
WHERE productname like concat_ws('%', #S, '%');
````````````````````````````````````````````````````````````````

Simply use CONCAT to ensure wildcards on either side of variable value. Otherwise, CONCAT_WS which uses first argument as separator returns double wildcards at the end of string which is equivalent to single wildcard and yields undesired results.
LIKE 'product%%'
LIKE 'product%'
However, CONCAT will return wildcards as you expect:
LIKE '%product%'

Related

Regex bring just the match MySQL

I am trying to getting just the first two words on sql query, I am using the match: ^\w{2}- but with no success because nothing is coming to me, I need to get those values
BA, CE, DF, ES, GO, I don't know how can I do that, below some data example.
SC&Tipo=FM
SC&Tipo=Web
SC&Tipo=Comunitaria
RS&Tipo=Todas
RS&Tipo=AM
RS&Tipo=FM
RS&Tipo=Web
RS&Tipo=Comunitaria
BA-Salvador&Tipo=12horas
CE-Fortaleza&Tipo=12horas
CE-Interior&Tipo=12horas
DF-Brasilia&Tipo=12horas
ES-Interior&Tipo=12horas
ES-Vitoria&Tipo=12horas
GO-Goiania&Tipo=12horas
MG-ZonaDaMata/LestedeMinas&Tipo=12horas
MG-AltoParanaiba&Tipo=12horas
MG-BeloHorizonte&Tipo=12horas
MG-CentroOestedeMinas&Tipo=12horas
Query: SELECT * FROM tabel WHERE filter REGEXP '^\w{2}-'
EDIT SOLVED:
To solve the query should be:
SELECT SUBSTRING(column, 1, 2) AS column FROM table WHERE column REGEXP '^[[:alnum:]_]{2}-'
MySQL doesn't support the character class \w or \d. Instead of \w you have to use [[:alnum:]]. You can find all the supported character classes on the official MySQL documentation.
So you can use the following solution using REGEXP:
SELECT *
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-'
You can use the following to get the result with regular expression too, using REGEXP_SUBSTR:
SELECT REGEXP_SUBSTR(filter, '^[[:alnum:]]{2}-')
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-';
Or another solution using HAVING to filter the result:
SELECT REGEXP_SUBSTR(filter, '^[[:alnum:]]{2}-') AS colResult
FROM table_name
HAVING colResult IS NOT NULL;
To get the value before MySQL 8.0 you can use the following with LEFT:
SELECT LEFT(filter, 3)
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-';
demo: https://www.db-fiddle.com/f/7mJEmCkEiYhCYK3PcEZTNE/0
Using SUBSTRING(<column>, 1, 2) should also work..
More or less like below
SELECT
<column>
, SUBSTRING(<column>, 1, 2)
FROM
<table>
WHERE
SUBSTRING(<column>, 1, 2) IN ('BA' [,<value>..])
Some things are BNF (Backus-Naur form) in the SQL code.
<..> means replace with what you need.
[, ..] means optional unlimited repeat the comma in there is part off SQL syntax

extract a pattern number from url mysql or python

I have a bunch url that has a string either has
hotel+4 digit number: hotel1234
or slash+4digit.html: /1234.html
Is there a regex to extract 4 digit number like 1234 either use python or mysql?
I'm thinking 'hotel'[0-9][0-9][0-9][0-9],sth like this
Thanks!
You can try the REGEXP
SELECT * FROM Table WHERE ColumnName REGEXP '^[0-9]{4}$'
or
SELECT * FROM Table WHERE ColumnName REGEXP '^[[:digit:]]{4}$';
The following is a stackoverflow.com link that might be useful showing
how to extract a substring from inside a string in Python?
Unfortunately, MySQL regexp simply returns true if the string exists. I have found substring_index useful if you know the text surrounding the target...
select case when ColumnName like 'hotel____' then substring_index(ColumnName,'hotel',-1)
when ColumnName like '/____.html' then substring_index(substring_index(ColumnName,'/',-1),'.html',1)
else ColumnName
end digit_extraction
from TableName
where ...;
The case statement above isn't necessary because of the way substring_index works (by returning the entire string if the search string isn't found).
select substring_index(substring_index(substring_index(ColumnName,'hotel',-1),'/',-1),'.html',1)
from TableName
where ...;

How to use SQL to remove superfluous characters from names?

How do I remove all superfluous full-stop . and semi-colon ; characters from end of last name field values in SQL?
One way to check of the last character is a "full stop" or "semicolon" is to use a substring function to get the last character, and compare that to the characters you are looking for. (There are several ways to do this, for example, using LIKE or REGEXP operator.
If that last character matches, then lop off that last character. One way to do that is to use a substring function. (Use the CHAR_LENGTH function to return the number of characters in the string.)
For example, something like this:
UPDATE mytable t
SET t.last_name = SUBSTR(t.last_name,1,CHAR_LENGTH(t.last_name)-1)
WHERE SUBSTRING(t.last_name,CHAR_LENGTH(t.last_name),1) IN ('.',';')
But, I'd strongly recommend that you test those expressions using a SELECT statement, before running an UPDATE statement.
SELECT t.last_name AS old_val
, SUBSTR(t.last_name,1,CHAR_LENGTH(t.last_name)-1) AS new_val
FROM mytable t
WHERE SUBSTRING(t.last_name,CHAR_LENGTH(t.last_name),1) IN ('.',';')
Substring rows that have a semi-colon or dot :
update emp
set ename = substring(ename, 1, char_length(ename) - 1)
where ename REGEXP '[.;]$';

Using replace and concat in MySQL

I have strings values such as the following in a column:
|333|,|331|
I want to perform a balanced string replacement as follows:
xxTM_333_TMxx,xxTM_331_TMxx
I have tried to do this with the REPLACE and CONCAT functions but didn't get the desired output.
For example:
SELECT REPLACE('|333|,|331|','|','xxTM');
This replaces one of the | symbols correctly in each case, but not its matched (balanced) counterpart.
How can I achieve this result in MySQL?
SET #st := '|333|,|331|';
SELECT
CASE WHEN #st LIKE '|%|' THEN
CONCAT(
'xxTM',
REPLACE(REPLACE(#st, '|,|', '_TMxx,xxTM_'), '|', '_'),
'TMxx')
END rep_st;
Please see fiddle here.

mysql substr not working like php

Please help me resolve my query when using query - I just want to subtract a few characters and then use the % to find the matching LIKE:
select * from `providers` WHERE `name` LIKE SUBSTR('telin',1,4)%
Please let me know what i'm doing wrong, any kind of help is greatly appreciated!
Assuming telin is a column name rather than the literal string, it should be quoted in backticks. If it is the literal string, then there is obviously no need to extract a substring from it. I suspect however, that it was the result of a PHP variable you pasted here after echoing out the full query, then it is correctly single-quoted.
Anyway, you will need to concatenate the SUBSTR() result onto the '%' via CONCAT():
SELECT * FROM `providers` WHERE `name` LIKE CONCAT(SUBSTR(`telin`,1,4), '%');
But better would be to use LEFT() to compare the first 4 characters of each:
SELECT * FROM `providers` WHERE LEFT(`name`, 4) = LEFT(`telin`,4);