regular expression search a number from string - mysql

this question maybe very simple for you. i'm using mysql regexp statment.
myQuery is
select * from contents where categories regexp '{myPattern}';
categories field area 54,25,99,4,2... etc string.
my question how can i find only number of '4' from categories field.
sorry for my english.
help me please.

… WHERE FIND_IN_SET('4', categories) > 0
better yet to normalize your db scheme with categories in their own table and then join these tables together m:n

The way to match "any cvs string containing '4' as a value in the string" is:
mycolumn regexp '[[:<:]]4[[:>:]]'
In mysql regex, [[:<:]] means "start of word" and [[:>:]] means "end of word".

You can use this:
where categories RLIKE '(^|,)4($|,)';
This will match when categories contains 4, followed by a , or nothing, and precedeed by , or nothing.

Related

Can anyone tell me in mysql How to display employee names whose name DO NOT start with alphabet A?

I am a beginner so please help me.
There are 2 things you need to combine in this case.
Because you didn't provide enough information in your question we have to guess what you mean by name. I'm going to assume that you have a single name column, but that would be unusual.
With strings, to match a character column that is not an exact match, you need to use LIKE which allows for wildcards.
You also need to negate the match, or in other words show things that are NOT (something).
First to match names that START with 'A'.
SELECT * FROM table_name WHERE name LIKE 'A%';
This should get you all the PEOPLE who have names that "Start with A".
Some databases are case sensitive. I'm not going to deal with that issue. If you were using MySQL that is not an issue. Case sensitivity is not universal. In some RDBMS like Oracle you have to take some steps to deal with mixed case in a column.
Now to deal with what you actually want, which is NOT (starting with A).
SELECT * FROM table_name WHERE name NOT LIKE 'A%';
your question should have more detail however you can use the substr function
SELECT name FROM yourtable
WHERE SUBSTR(name,1,1) <> 'A'
complete list of mysql string functions here
mysql docs
NOT REGXP operator
MySQL NOT REGXP is used to perform a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression.
Syntax:
expr NOT REGEXP pat
Query:
SELECT * FROM emp_table WHERE emp_name NOT REGEXP '^[a]';
or
SELECT * FROM emp_table WHERE emp_name NOT REGEXP '^a';

mySQL pattern matching a comma separated list

I have a mySQL table that contains restaurant information. Part of that information is a comma separated list of numbers that corresponds to the type of cuisine the restaurant serves. I'm having some problems getting the correct information out of the database. Table looks like
id businessName cuisine_id
1 Pizza Place 2,3,4,
2 Burger Place 12,13,14,
I came up with
SELECT * FROM restaurant WHERE cuisine_id LIKE "%2,%"
But that leaves me with the problem that it matches "2," "12," and 22,".
I also tried
SELECT * FROM restaurant WHERE cuisine_id LIKE "[^0-9]2,%"
But that returned nothing.
Any advice on how to write this expression?
Use regexp
SELECT * FROM restaurant WHERE cuisine_id REGEXP "(^|,)2,"
For num exact match,
SELECT * FROM restaurant WHERE cuisine_id regexp "(^|,)2(,|$)"
Note that ^, $ are mentioned as regex anchors which matches the start and end end of a line. This (^|,) will match either a start of a line or comma. So this ensured that the following pattern must be at the start or preceeded by comma.
There's no need to use regular expressions, you could use FIND_IN_SET string function:
SELECT * FROM restaurant WHERE FIND_IN_SET('2', cuisine_id)>0
or use CONCAT:
SELECT * FROM restaurant WHERE CONCAT(',', cuisine_id, ',') LIKE '%,2,%'
or better to normalize your database structure (is often not a good idea to store comma separated values in a single field)

MySQL - need to find records without a period in them

I've been to the regexp page on the MySQL website and am having trouble getting the query right. I have a list of links and I want to find invalid links that do not contain a period. Here's my code that doesn't work:
select * from `links` where (url REGEXP '[^\\.]')
It's returning all rows in the entire database. I just want it to show me the rows where 'url' doesn't contain a period. Thanks for your help!
SELECT c1 FROM t1 WHERE c1 NOT LIKE '%.%'
Your regexp matches anything that contains a character that isn't a period. So if it contains foo.bar, the regexp matches the f and succeeds. You can do:
WHERE url REGEXP '^[^.]*$'
The anchors and repetition operator make this check that every character is not a period. Or you can do:
WHERE LOCATE(url, '.') = 0
BTW, you don't need to escape . when it's inside [] in a regexp.
Using regexp seems like an overkill here. A simple like operator would do the trick:
SELECT * FROM `links` WHERE url NOT LIKE '%.%
EDIT:
Having said that, if you really want to negate regexp, just use not regexp:
SELECT * FROM `links` WHERE url NOT REGEXP '[\\.]';

MySQL wildcard Like query with multiple words

I have a mysql query as follows.
$query="SELECT name,activity FROM appid
where result > 5 AND name LIKE :term ORDER BY name ASC LIMIT 0,40";
$result = $pdo->prepare($query);
$result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR);
$result->execute();
What i want to do is this.
I have and entry like this that i want to find
'News & Weather'
However when i type
'news weather'
it of course will not find it. How can i be able to type that and retrieve that entry?
Regular expressions can do the trick:
select *
from appid
where name rlike 'news|weather' -- Matches 'news' or 'weather'
Another example:
select *
from appid
where name rlike 'news.*weather' -- Matches 'news' and 'wether'
-- with any characters in-between or none at all
-- (ordered)
Just one more:
select *
from appid
where name rlike '^news.{1,}weather$' -- Matches any text that starts with 'news'
-- and has at least one character before
-- ending with 'weather'
Regular espressions can be used to create very complicated filters on text fields. Read the link above for more information.
If you can add a full-text index to your table, Full-text search might be the better way to go with this. Specifically, a boolean Full-Text search:
select *
from appid
where match(name) against (+news +weather)
I believe the only way possible are through code:
Option A: Replace the spaces in your query parameter with '%' in code, but that of course will make the multiple words ordered
Option B: Split your parameter on spaces and dynamically construct your query with as many LIKEs as needed, adding additional ":termN" parameters for each one.

Mysql REGEXP how to do an exact match

i have a notes column which contains text and has an id within the text, something like
"some random text (actvityid - 1234)"
i need to pull out the id 1234 in this case and update the activityid column within the same table.
my query looks like this
"UPDATE table_name SET activityId = {$f['activityId']} WHERE notes REGEXP '{$f['activityId']}' "
the problem with this is if $f['activityId'] is 34 or 123 for example it still updates the activityid column with that value. How can i do an exact match on "1234" and update only if it matches the whole string, here "1234".
Many thanks.
WHERE notes REGEXP CONCAT('(actvityid - ', {$f['activityId']}, ')')
or
WHERE notes REGEXP '[[:<:]]{$f['activityId']}[[:>:]]'
[[:<:]] and [[:>:]] stands for word boundaries.
No need to use CONCAT if variable is passed from PHP,
and no need to use REGEXP if you match exact string without special characters
WHERE notes LIKE '%(actvityid - {$f['activityId']})%'