mysql query that looks for a value in a string - php

I am wondering if i can put something in my query which searches for a word within a string. For example, if i have a field named user_purchased, i want to query it and pull only records where the word 'dog' exists within the string.
I know i can do this using php like this
(!stristr($row['user_purchased'], 'dog'))
BUT, i'm wondering if i can do this in the query itself instead and that this will perhaps speed up performance.
Thanks in advance for help on this

You can use LIKE:
WHERE your_col LIKE '%dog%'
If you want better performance you could look at a full text search. This uses a FULLTEXT index to quickly find the matching rows.

In MySql, you can use INSTR(str,substr)
Quote from the MySql manual at http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instr
INSTR(str,substr)
Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the order of the arguments is reversed.
mysql> SELECT INSTR('foobarbar', 'bar');
-> 4
mysql> SELECT INSTR('xbar', 'foobar');
-> 0
This function is multi-byte safe, and is case sensitive only if at least one argument is a binary string.

SELECT * FROM table WHERE user_purchased LIKE '%dog%';

Related

How to implement Full Text search in InnoDB?

I have a query,
e.g.
name column have "Rodrigue Dattatray Desilva".
I want to write a query in such a way that,
If I search for 'gtl' and match anywhere in string it should show the result.
I know in PHP I can apply the patch like '%g%t%l%'.
But I want to know MySql way.
Note: I can search for anything, I am just giving above an example.
EDIT:
create table Test(id integer, title varchar(100));
insert into Test(id, title) values(1, "Rodrigue Dattatray Desilva");
select * from Test where title like '%g%t%l%';
Consider the above case. Where "gtl" is string I am trying to search in the title but search string can be anything.
gtl is string where it exists in the current title but not in sequence.
The easy answer is that you need an extra wildcard:
select * from Test where title like '%g%t%l%';
The query you posted does not have a wild card after the 'l', so would only match if the phrase ended with 'l'.
The more complicated answer is that you can also use regular expressions, which give you more power over the search.
The even more complicated answer is that performance of these string matching queries tends to be poor - the wild cards mean that indexes are usually ineffective. If you have a large number of rows in your table, full-text searching is much faster.
You can do the same in Mysql too.
You can use the keyword like in MySql.
% - The percent sign represents zero, one, or multiple characters
_ - The underscore represents a single character

How to check if one whole string is present in part of another string in PHP

I'm using PHP for a school project and I'm trying to run an SQL query that will return a list of entries in a table where they all contain 8 digits of a 12 digit ID. E.g. I have a string containing "0221122017" and I want to query this to return a list of values that resemble "0221122017XXXX". Is there an easy way to do this? I have not been able to find that carries out this sort of function for an SQL Query. I have no problem with the PHP side and running a query etc. I am really just racking my brains as to how this would be done. I hope I have explained my problem well
Thanks
You can use LIKE
SELECT *
FROM yourTable
WHERE id LIKE '%0221122017%'
LIKE is followed by a pattern string, and % is a wildcard that matches anything.

How to check if a column value is in a string SQL

I have a database with 150,000 records and I need to match its FULL column value or records, with some parts of the string.
**
As i want to check if the STRING contains the COLUMN records and NOT!
if the COLUMN contains the string
**
(Example below)
For testing purposes
Lets say the database has a TABLE , 1 COLUMN and 1 record as the records are similar to this:
come to me
and i need to match it with this #STRING
She wants to come to me now
I want to execute something similar to :(but this doesn't work of course)
SELECT * from TABLE where #STRING like '%'+COLUMN+'%'
I can't seem to solve this with SQL the usage of PHP is possible but prefer if the solution is with SQL but if the solution with PHP is available please propose it and note that the database has over 150,000 records
SELECT * from TABLE where LOCATE(COLUMN, #STRING)>0;
LOCATE(a,b) returns a number giving the character location of a in b, or returns 0.
See Mysql LOCATE()
The docs discuss that LOCATE() is only case sensitive when one of the strings is a 'binary string'. That probably doesn't affect your use case, though if it became an issue you could CONVERT() the binary strings to a locale and use LOWER() to get lower case.
MySQL String Functions
The dynamic like syntax for mysql is
SELECT * from TABLE where #STRING like CONCAT('%',COLUMN,'%')

Querying a table where the field contains any order of given text strings

I want to query a table as follows:
I have a field called "category" and my input match contains N separate words. I want the query to match all rows that contain all N words, but in any order.
For example if the field category contains "hello good morning world", my input query can contain "hello morning" or "good" or "world hello" and all are matches to the query.
How do I formulate such an SQL expression?
Also it would be good if the query can be made case insensitive.
If you are using MySQL you can use the boolean fulltext search feature to achieve this. You can put a + in front of each term and then only results with all the terms, in any order, will be returned. You will need to make sure the column containing the category field has a fulltext index specified on it for this to work. Other database engines probably have similar features. So for example you might do something like the following assuming there were a fulltext index over the category column...
SELECT * FROM myTable WHERE MATCH (category) AGAINST ('+term1 +term2 +term3' IN BOOLEAN MODE);
I would avoid using the "LIKE" operator as others have suggested you would have to worry about the headache of mixed upper/lower case and if you have a large database using a % in the front of a LIKE search term is going to cause a full table scan instead of using an index which is horrible for performance.
I'm not writing the loop that will build this query for you. This will get the job done, but it will be pretty inefficient.
SELECT * FROM table
WHERE (
TOUPPER(category) LIKE '*HELLO*' AND
TOUPPER(category) LIKE '*GOOD*' AND
TOUPPER(category) LIKE '*MORNING*' AND
TOUPPER(category) LIKE '*WORLD*'
);
You could also research using REGEXes with SQL.

mysql search database against a query

I'm looking for a way to compare database values against a given query using MySql
(in oppose of searching the query in the db)
I will elaborate:
I have a table that holds comma separated keywords and a result for each block of keywords
for example :
col 1 col 2
Mercedes,BMW,Subaru car
Marlboro,Winston cigarette
today im taking the user query (for example - Marlboroligt)
as you can see if i will search for the value 'Marlboroligt' in the db i will get no results.
for that matter i want to search 'Marlboro' from the db inside the query and return 'cigarette'
Hope my explanation is sufficient and that this is actually possible :-).
Normalization will help you the most. Otherwise, search in comma delimited fields is discussed here:
Select all where field contains string separated by comma
...and to search 'Marlboroligt' instead of 'Marlboro Light', you can try looking into the LEVENSHTEIN function, or maybe the Soundex encoding (which looks like too little bang for too large a buck, but then again, maybe...).
I see the following possible solutions:
setup a keyword-search engine like Sphinx and use it to search keywords in your db
normalize your db - col1 must contain the only keyword
use like patterns
select col2 from mytable where col1 like "%Marlboro%"
like slows down your application and can have substring-related issues.

Categories