I have a MySql database with some rows as follows:
ID DESC
1 This is my bike
2 Motorbikes are great
3 All bikers should wear helmets
4 A bike is great for exercise
5 A. Top. Bike.
What I want to do is return the rows with whitespace surrounding the search term, OR the term being at the end or beginning of the description.
For example,
"SELECT * FROM `mytable` WHERE `desc` LIKE '%bike%'"
Will return all rows. But,
"SELECT * FROM `mytable` WHERE `desc` LIKE '% bike %'
Will only return row 4.
What I really want is a reliable way to return rows 1, 4 and 5, i.e. where the search term is sorrounded with anything BUT chars A-z, 0-9. Any ideas? Is this even possible with MySql?
Thanks!!
You can use regular expressions in SQL
SELECT * FROM `table` WHERE desc REGEXP '\bbike\b'
You should start reading about MySql RegEx.
Sample Code.
SELECT * FROM table WHERE field_name REGEXP PATTERN;
More Specific
details Table
ID NAME
1 Dipesh
2 Dip
3 Dipe
4 DiDi
5 Di
SELECT * FROM details WHERE NAME REGEXP '^Di$';
Result
NAME -> Di
SELECT * FROM details WHERE NAME REGEXP 'Di$';
Result
NAME -> DiDi , Di
SELECT * FROM details WHERE NAME REGEXP '^Di';
Result
NAME -> Dip, DiDi, Di
You need to specify the additional conditions in the query:
SELECT *
FROM `mytable`
WHERE
`desc` LIKE '% bike %' OR
`desc` LIKE '% bike' OR
`desc` LIKE 'bike %';
Try this one, hope it'll help you
"SELECT * FROM `mytable` WHERE `desc` LIKE '% bike'
Related
I am doing a search in two text fields called Subject and Text for a specific keyword. To do this I use the LIKE statement. I have encountered a problem when trying to sort the results by the number of occurrences.
my search query looks like this:
SELECT * FROM Table WHERE (Text LIKE '%Keyword%' OR Subject LIKE '%Keyword%')
I tried to add a count() statement and sort it by the number of occurrences, but the count() statement just keep returning the number of rows in my table.
Here is the query with count statement:
SELECT *, COUNT(Text LIKE '%Keyword%') AS cnt FROM News WHERE (Text LIKE '%Keyword%' OR Subject LIKE '%Keyword%') ORDER BY cnt
What im looking for is something that returns the number of matches on the Subject and Text columns on each row, and then order the result after the highest amount of occurrences of the keyword on each row.
Below query can give you the no.of occurrences of string appears in both columns i.e text and subject and will sort results by the criteria but this will not be a good solution performance wise its better to sort the results in your application code level
SELECT *,
(LENGTH(`Text`) - LENGTH(REPLACE(`Text`, 'Keyword', ''))) / LENGTH('Keyword')
+
(LENGTH(`Subject`) - LENGTH(REPLACE(`Subject`, 'Keyword', ''))) / LENGTH('Keyword') `occurences`
FROM
`Table`
WHERE (Text LIKE '%Keyword%' OR Subject LIKE '%Keyword%')
ORDER BY `occurences` DESC
Fiddle Demo
Suggested by #lserni a more cleaner way of calculation of occurrences
SELECT *,
(LENGTH(`Text`) - LENGTH(REPLACE(`Text`, 'test', ''))) / LENGTH('test') `appears_in_text`,
(LENGTH(`Subject`) - LENGTH(REPLACE(`Subject`, 'test', ''))) / LENGTH('test') `appears_in_subject`,
(LENGTH(CONCAT(`Text`,' ',`Subject`)) - LENGTH(REPLACE(CONCAT(`Text`,' ',`Subject`), 'test', ''))) / LENGTH('test') `occurences`
FROM
`Table1`
WHERE (TEXT LIKE '%test%' OR SUBJECT LIKE '%test%')
ORDER BY `occurences` DESC
Fiddle Demo 2
You want SUM instead. Count will count how many records have non-null values, which means ALL matches and NON-matches will be counted.
SELECT *, SUM(Text LIKE '%Keyword') AS total_matches
...
ORDER BY total_matches
SUM() will count up how many boolean true results the LIKE produces, which will be typecast to integers, so you get a result like 1+1+1+0+1 = 4, instead of the 5 non-nulls count.
// escape $keyword for mysql
$keyword = strtolower('Keyword');
// now build the query
$query = <<<SQL
SELECT *,
((LENGTH(`Subject`) - LENGTH(REPLACE(LOWER(`Subject`), '{$keyword}', ''))) / LENGTH('{$keyword}')) AS `CountInSubject`,
((LENGTH(`Text`) - LENGTH(REPLACE(LOWER(`Text`), '{$keyword}', ''))) / LENGTH('{$keyword}')) AS `CountInText`
FROM `News`
WHERE (`Text` LIKE '%{$keyword}%' OR `Subject` LIKE '%{$keyword}%')
ORDER BY (`CountInSubject` + `CountInText`) DESC;
SQL;
Returns number of occurrences in each field and sorts by that.
The 'keyword' needs to be lower cased for this to work. I don't think it's really fast, performance wise as it needs to lower-case fields and there's no case-insensitive search in MySQL afaik.
You could index each news item (subject and text) by words and store in another table with news_id and occurrence count and then match against that.
This is my table:
ID NAME GROUP
123456 Example 1
789012 Test 2
345678 Lorem 1
This code works fine:
select * from mytable where id="789012"
However, this code fails:
select * from mytable where group="1"
Why is this? Isn't the whole point of iterating with the while loop to return multiple rows?
Your query fails. You need to escape reserved words in MySQL like group with backticks
select * from mytable where `group` = 1
I am trying to all grab rows of data from a data table, where one word matches a word within the text in my column 'story'.
Table Structure:
post_id | user_id | story
----------------------------------
1 | 1 | Hello World What's up?
2 | 4 | Hello guys!
3 | 7 | Working on shareit.me!
For Example:
I want to grab all of the posts containing the word hello (I am looking for case-insensitive).
How can I do this?
Here is what I have done so far:
// this will be the keyword! so use the variable $filter_tag in the query!
$filter_tag= $_GET['tag'];
//query for getting the users' posts containing the select tag
$query_posts= "SELECT * FROM posts WHERE user_id= '$user_id' ORDER BY post_id
DESC";
$result_posts= mysqli_query($connect, $query_posts);
Thanks!
$query_posts= "SELECT * FROM posts WHERE user_id= '$user_id' AND story LIKE '%$filter_tag%' ORDER BY post_id
DESC";
SELECT * FROM posts WHERE ... AND LOWER(story) LIKE '%hello%'
OR
SELECT * FROM posts WHERE ...
AND story COLLATE latin1_general_ci_ai LIKE '%hello%'
It would be:
SELECT * FROM posts WHERE ... AND story LIKE '%hello%'.
Generally the "%" is a wildcard (like '*'). So you can use 'hello%' '%hello%' and so on.
You can use the LIKE operator:
$query_posts = "SELECT * FROM posts WHERE user_id = $user_id AND story LIKE '%yourword%' ORDER BY post_id";
The % characters are like wildcards. % means match any number of characters, where _ (underscore) matches just one.
Note: I've removed the single quotes from your user_id column check too - this, being an integer, doesn't want to be in quotes - they are for strings.
Goes without say don't forget to escape the input.
$query_posts= "SELECT * FROM posts WHERE user_id = '$user_id' AND story LIKE '%".mysql_real_escape_string($filter_tag)."%'";
My answer is like the same, i made a sqlfiddle:
#supose the tag is Hello
SELECT * FROM posts
where story like "%Hello%";
PS: http://sqlfiddle.com/#!2/6bfcc1/5
The best solution will be to use MATCH() AGAINST() with an FULLTEXT index.
I have a database table named
group(group_name, admin_name);
I've designed a form for searching the group (A Simple TextBox and a Search Button)
Now the query is, whatever the user enters into the TextBox, it should search the string into the entire table and return the values (i.e. Group Name and Admin Name)
I can do this for only a single column
$text = // the String entered by User;
SELECT * FROM `group` WHERE `group_name` LIKE '%$text%'; (For group_name column)
SELECT * FROM `group` WHERE `admin_name` LIKE '%$text%'; (For admin_name column)
I want to do it for both....
I use this for both columns
SELECT * FROM group WHERE group_name LIKE '%$text%' or admin_name LIKE '%$text%';
Here I'm getting Duplicate values
I want to make it like a Search Engine
Please Help
Try-
SELECT DISTINCT * FROM `group` WHERE `group_name` LIKE '%$text%' or `admin_name` LIKE '%$text%';
You can use distinct and group them in where
SELECT DISTINCT *
FROM group
WHERE (group_name LIKE '%$text%'
or admin_name LIKE '%$text%');
for looking up matching keywords in mysql i use
SELECT * FROM `test` WHERE `keywords` REGEXP '.*(word1|word2|word3).*' LIMIT 1
I want to order them by the most matching keywords in the keywords column to give the best answer.For example
Keywords /////////////// Response
word1,word2 /////////// test1
word1,word2,word3 / test2
I want the response to be test2 with the query given.
How can i order the results my the most matching keywords?
SELECT
(keywords REGEXP '.*(word1).*')
+(keywords REGEXP '.*(word2).*')
+(keywords REGEXP '.*(word3).*') as number_of_matches
,keywords
,field1
,field2
FROM test
WHERE keywords REGEXP '.*(word1|word2|word3).*'
ORDER BY number_of_matches DESC
LIMIT 20 OFFSET 0