Searching a keyword in a long string in mysql? - php

keyword = house
SELECT * FROM products WHERE description LIKE '%house%'
This query also returns records having keyword, for example, courthouse, but I want to look for house only. How do I search anywhere in the description for "house" only?
Thanks.
UPDATE
just for more clarification ..
actually house, can be at
- the start of the description .. "House for sale..",
- can be quoted -- "house", 'house'
- can have exclamation .. house!!!, house!
- others - house? etc ..
this is why I used %house%

Are you looking for longs strings containing the whole word?
Search for "whole word match" in MySQL

SELECT * FROM products WHERE description rlike '[[:<:]]house[[:>:]]'
rlike is synonim for REGEXP.
[[:<:]] denotes the start of the word and the
[[:>:]] end of the word.
It works for all your requirements (case insensitive, with quoted words or words ending, or begging, with exclamation points and other non-letter characters)

The % before and after will search any matching text before and after the search keyword, try this instead for exact search:
SELECT * FROM products WHERE description = 'house'

Simple thing only house means, use this
SELECT * FROM products WHERE description = 'house'
If you want any word contain house in backside means use this,
SELECT * FROM products WHERE description LIKE '%house'
If you want any word contain house in frontside means use this,
SELECT * FROM products WHERE description LIKE 'house%'
If you want any word contain house in anywhere in description means use this,
SELECT * FROM products WHERE description LIKE '%house%'

Try a space around the keyword:
SELECT * FROM products WHERE description LIKE '% house %' OR description LIKE 'house %' OR description LIKE '% house' OR description LIKE '% house%'
Edit: added more options in search. The last one would allow for house. or house,, though something like housecat would also match. Regex would work best here. This solution came from Astandar, who deleted his answer.

Related

Mysql Search Postcodes

I want to create a mysql search query, that will search for postcodes here is what i have done so far
SELECT * FROM orders where ( InvoicePostcode LIKE 'b%' OR InvoicePostcode LIKE 'ws%') order by InvoiceNumber asc
I want to display only postcode starting with b or ws but the problem is some post contain bb or BS at the start of the postcode for example
BS24 8EE
BB9 8SY
the only ones that should be showing that start with b like this one B65 0NQ im not sure how to check postcode by only looking at the letter at the start before the numbers in the postcode
You can try to use regexp to exclude certain pattern:
In the below I exclude InvoicePostcode containing B followed by a letter
SELECT * FROM orders
WHERE (InvoicePostcode LIKE 'b%' AND NOT InvoicePostcode RLIKE '^(B[A-Z])')
OR (InvoicePostcode LIKE 'ws%' AND NOT InvoicePostcode RLIKE '^(WS[A-Z])')
ORDER BY InvoiceNumber ASC
You can use pattern matching to solve this issue.
What you need to know is the pattern you are searching for, to give you an example if you are searching for all postcodes starting with B only then you know that these postcodes will
Must have first character as B. There are examples in link to select first character (^) and 1 instance({1} equal to 'B' or 'b'.
Second character can be any number
Similarly you can do for all other patterns as well.
You can use REGEXP clause for the same.
E.g.:
select * from orders where (InvoicePostcode REGEXP '^B[^BS].' OR InvoicePostcode REGEXP '^WS.')
'^B[^BS].*' in this it will ignore words start with BB OR BS.
Hope it'll help you out.
SELECT * FROM orders
WHERE (InvoicePostcode LIKE 'b%' AND NOT InvoicePostcode RLIKE '^(B[A-Z])')
OR (InvoicePostcode LIKE 'ws%' AND NOT InvoicePostcode RLIKE '^(WS[A-Z])')
ORDER BY InvoiceNumber ASC
pls refer : https://www.guru99.com/regular-expressions.html
RLIKE operator performs a pattern match of a string expression against a pattern. The pattern is supplied as an argument. The following MySQL statement will find the author’s name beginning with ‘B’. The ‘^’ have been used to match the beginning of the name.
SELECT * FROM orders WHERE InvoicePostcode RLIKE '^B';
[A-Z]
Matches any uppercase letter​
[a-z]
Matches any lowercase letter​
'^(B[A-Z])'means it will work as first letter B and whether next is A to Z are not.

Exclude results from a mysql query using regexp

I got a table with the following values
titles:
Accountant
Auditor
Bookkeper
Forensic Accountant
Tax Accountant
I'd like to select all the titles that don't contain "Accountant" in it, i'm currently trying with
SELECT * FROM careers WHERE title NOT REGEXP '^Accountant'
But it still selects "Forensic Accountant" and "Tax Accountant"
Any thoughts?
Thanks in advance!
use not like instead of regexp:
SELECT * FROM careers WHERE title NOT LIKE '%Accountant%'
See the SQLFiddle
You can use LIKE instead of REGEXP like this:
SELECT * FROM careers WHERE title NOT LIKE '%Accountant%';
The regex is wrong, you are using the caret(^) , which means the words you are excluding should start with Accountant, instead remove the caret and you should be good
SELECT * FROM careers WHERE title NOT REGEXP 'Accountant'
To exclude something user defined, based on what jobtitle is selected, do something like the following
SELECT * FROM careers WHERE title NOT REGEXP (SELECT regexMatch FROM careers WHERE title = "Tax Accountant")

PHP: searching for a word in a string in mysql?

I'm trying to search for a word in a string in mysql database using PHP.
the issue that I am having is that it searches and spits out the result on my PHP page but any word that is close to the searched word is also gets a result on my page.
to explain this better, lets say I have a string which is like this:
women's clothing
now if i search for a word which is women the results are being displayed on my page correctly But If i search for the word men the same results are being displayed on my page because the word women has the word men in it.
this is my current sql query:
SELECT id, category_name, image_url FROM data WHERE `category_name` LIKE '%$sub%' GROUP BY category_name
I tried to change '%$sub%' to '$sub' but that doesn't return any results at all!
could someone please advise on this?
Edit:
the strings in the category_name column vary and they cannot be changed since they are coming from an external API.
these strings could vary. so one might look like Women's Dresses & Skirts and another one might look like Women's shoes and another one might look Women's bags and another one might look like men's shoes etc etc....
so what i need to do is to display all the results for the keyword women and display the results for all the men. I hope that makes sense.
but at the moment, the results of men and women being displayed at the same time because the word Women has the word Men in it as I explained above.
You can do this with MySQL's REGEXP operator, using word match.
SELECT ... WHERE column REGEXP '[[:<:]]$sub[[:>:]]' ...
okay guys, thanks for all your inputs. this is how I did it and its working now:
SELECT id, category_name, aw_image_url FROM data WHERE category_name RLIKE '[[:<:]]".$sub."[[:>:]]' GROUP BY category_name
The thing with what you want, is that you want men's clothing to show up but nothing that has something like women. The only difference between these 2 results is that woMEN has characters in front of it and MEN's clothing has characters after.
Mrun his idea is if you want to search for the exact word followed by nothing. So when you use: LIKE '% $sub %' only results that have the word MEN followed by nothing and nothing in front of the word MEN directly. There has to be a space in between.
Now for your result to work, you can use: LIKE $sub% (without the space at the end), however this does mean the word MEN can be followed by anthing. So for example the word MENACE would show up. If you want specific characters only allowed like #mrun suggested, you can add anything between $sub and the % sign. You'd have to escape it though.
EDIT:
Now that I think of it, you'd probably want MENS to be allowed as well but that means you'll have to choose your own conditions cause there's no way for MYSQL to automatically detect that the plural form of a word is allowed as well etc.
There are several options for this. Here's one of them:
SELECT id, category_name, image_url FROM data WHERE `category_name` LIKE '% $sub %' OR `category_name` LIKE '% $sub' OR `category_name` LIKE '$sub' OR `category_name` LIKE '$sub %' OR `category_name` LIKE '% $sub\' %' OR `category_name` LIKE '% $sub' OR `category_name` LIKE '$sub\'' OR `category_name` LIKE '$sub\' %' GROUP BY category_name
Another way to do this is to use the MATCH AGAINST, but you will need to use the FULLTEXT index, here's how:
SELECT id, category_name, image_url FROM data WHERE MATCH (`category_name`) AGAINST ('+$sub' IN BOOLEAN MODE) GROUP BY category_name

MySQL query order by multiple items not working

I´m currently working on a query that must pull up titles ordered by
Exact match,
Followed by Highest amount of matched words first,
Followed by First word in query is first word in title,
Followed by Alphabetical order.
Something like this:
SELECT title
FROM title
WHERE title LIKE '%keyword%' OR LIKE '%keyword1%' OR LIKE '%keyword2%'
order by
case when title == 'keyword' then 0 else 1 end asc,
((title like '%keyword1%') + (title like '%keyword2%')) desc,
case when title like 'keyword1%' then 0 else 1 end asc,
title asc;
I tested with 8 titles.
Search: "Buford Christmas".
Result:
Buford Christmas
Christmas Buford
Mr Buford
Mr Buford
Buford and Lisa
Lisa Christmas
Me Christmas
Me Buford Lisa.
I need to find a way to sort the titles so that "Buford and Lisa" should be before "Mr Buford".
They keyword in the query may have any number of sub-keywords, causing the code in the MySQL statement to change dynamically. My example code was generated with a keyword that has 2 sub-keywords. The part that seems not to be working is: "case when title like 'keyword1%' then 0 else 1 end asc" I am wondering if the code is in the wrong position in the comma delimited order sequence or if I should assign different numbers to 'then' and 'else'.
About my select code:
In my select statement if the keyword is "Buford Christmas" it's broken into "Buford" and "Christmas" and "Buford Christmas".
About this part of order code:
((title like '%keyword1%') + (title like '%keyword2%')) desc,
MySQL treats boolean expressions as numbers, with true being 1. So, this counts the number of matches.
select title
from books
where title like '%buford christmas%'
or title like '%buford%'
or title like '%christmas%'
order by
case
when
title = 'buford christmas' then 1
when
title like '%buford%' and title like '%christmas%' then 2
when
title like 'buford%' then 3
when
title like '%buford%' then 4
when
title like 'christmas%' then 5
when
title like '%christmas%' then 6
end
asc;
This will do what you're looking for. Obviously substitute variables for the literals there. It prioritises results as such:
Books with title that EXACTLY matches the keywords
Books with titles that CONTAIN BOTH keywords
Books with titles that START with the first keyword
Books that CONTAIN the first keyword
Books that END with the last keyword
Books that CONTAIN the last keyword
Demo: http://sqlfiddle.com/#!9/ec62a/7
edit
You may also want to consider a fulltext index, eg: create fulltext index ftx_title on books(title), you could then run your query as such:
select *
from books
where match(title)
against ('buford christmas' in boolean mode);
Which would make crafting your queries for keywords quite a bit simpler

Using the MySQL like statement

Hello i am trying to get the like statement working however it will only work if its an exact match where as im am hoping to show all matches. So lets say you search "and" in the search bar, i want it to come back with all posts that have the word and in the title Below is the code
SELECT * FROM `Posts` WHERE title LIKE 'and'
Just trying to get this working in the phpmyadmin with the sql tab before i bother creating the actual full script.
Does anyone know how i can get the above statement to show all posts with and in the title?
Thanks for the help.
You have to put % before and after and.
SELECT * FROM `Posts` WHERE title LIKE '%and%'
Use:
SELECT * FROM `Posts` WHERE title LIKE '% and %'
Doing something like:
SELECT * FROM `Posts` WHERE title LIKE '%and%'
will include anything with and in it; sandy, for example.
try this placing % symbol
SELECT * FROM `Posts` WHERE title LIKE '%and%'
Do like this:
SELECT * FROM `Posts` WHERE title LIKE '%and%'
MySQL provides two wildcard characters for using with the LIKE operator, the percentage % and underscore _.
The percentage ( %) wildcard allows you to match any string of zero or more characters.
The underscore ( _) wildcard allows you to match any single character
Suppose you want to search for posts whose title starts with character ‘ and‘, you can use the percentage wildcard ( %) at the end of the pattern
SELECT * FROM `Posts` WHERE title LIKE '%and%'
If you know the searched string is embedded inside in the column, you can use the percentage ( %) wildcard at the beginning and the end of the pattern
SELECT * FROM `Posts` FROM books WHERE title REGEXP '[[:<:]]and[[:>:]]';
With this fiddle you are going to learn the differences when you use the wildcard operator(%):
select bar from foo where bar like "%h";
select bar from foo where bar like "%h%";
select bar from foo where bar like "h%";
Check the result here: http://sqlfiddle.com/#!2/1bc45f/2

Categories