Using LIKE in sql query - mysql

In a query in which I am looking for results based on the title of articles, I use the LIKE part as followed:
WHERE title LIKE %searchquery%
In my database one title is like this:
Economy in America
My problem:
With my current query, this title does NOT get listed, when the user enters the following searchquery:
america economy
When the user enters only one of these terms, everything works fine and the title gets listed.
How come?
How do I need to adjust my query so that my sql query will also work when the user enters more than one term?

The MySQL LIKE operator is limited in that it doesn't offer full regex support of the sort for which you are really looking. That being said, one option you could try would be to split your search query terms and then join multiple LIKE conditions using AND. Consider this example:
WHERE title LIKE %queryterm1% AND LIKE %queryterm2%
If queryterm1 be 'america' and queryterm2 be 'economy', then this would match the title 'Economy in America'.

You will need to split the query by whitespaces and then add multiple LIKE statements like this:
WHERE title LIKE '%america%' AND title LIKE '%economy%'

As #Tim says, you must write some routine in your application to divide the string terms and inject them in the select where clause. Or you may need to write some stored procedure for that.

Related

Extracting words from a paragraph and then match with existing database by Ms Access

I am the beginner on the usage of MS Access.
I am going to build a program in the MS Access 2007 which can scanning some specific wordings listed in the data table from a paragraph.
For example, I want to know the occurrences of the transportation taken by the students.
(i) Therefore, I set the words "school" and "Bus" in my datatable [tableA] fields [trans].
(ii) Then, I input "I go to school by bus." in the [Input] boxes.
(iii) The result i want is that the sun of occurrences of both "school" and "Bus" can be showed in the another one textbox.
In the current situation, i just create a query [QueryA] from the [tableA] and directly use the count function in the query form. And then set the criteria as " Like [forms]![tableA]![Input] & "*" ".
However, it can just match the words in the [Input] with the final count result of the Query.
Ths a lot for providing any advice, including new direction.
I hope I understand what you're asking here, so I'll give it a stab with the information that you've provided. In your SQL window, try the following script: NOTE: You will need to change the WHERE clause to reflect your Input box(s)
SELECT Count(*) AS Expr1
FROM tableA
WHERE tableA.[trans] Like '%[Input]%;

Fuzzy Logic sorting

Starting off, I apologize for bad table structure, it was not my decision and existed before me.
Anyway, I have a table tbl_cities that is a list of, you guessed it, cities (but for whatever reason are stored in column [desc]). I wanted to make a nifty AJAX text input that, as you type, it tries to find out what cities you are typing and offer them as suggestions. It's kinda like this example. So my query looked like this
SELECT [desc] FROM tbl_cities WHERE [desc] LIKE 'phil%'
Which works fine. However, I see there are a bunch of misspellings in this table, so I want to add fuzzy logic. I want to keep getting cities that match the first letters they type, so I have this query.
SELECT [desc] FROM tbl_cities WHERE [desc] LIKE 'phil%'
OR DIFFERENCE('phil', [desc])>3
Now I want to sort based on the [desc] LIKE 'phil%' before the fuzzy logic part. So in this example, Philadelphia should appear before random cities like PAOLA and POWELL
I would try something like that :
order by case when [desc] like 'phil%' then 0 else 1 end, [desc]

MYSQL Query to compare the results of two queries?

I am currently working on a search feature for a website that searches through a database for a specific animal.
Say the user inputs rabbit, the search will go through the db and display the results for rabbit.
Now say a user inputs bunny the search will go through the db but will not find a match for bunny.
Most people know that bunny means rabbit, but the database doesn't know that. At this point I have implemented a MySQL thesaurus within the same database to search for synonyms of what the user inputs.
This means that if the user inputs bunny it will display a list of synonyms for bunny.
In that list there is the word Rabbit and I am trying to pull that word out of there to generate a match. At this point I have the following.
"SELECT `engname` FROM `searchtestdb` WHERE `engname` IS NOT NULL ";
-- This displays the english name of every animal within that table. --
"SELECT synonyms.* FROM words LEFT JOIN synonyms ON synonyms.word_id = words.word_id WHERE word = \"$searchBox\""
-- This displays the synonyms for $searchBox which is the word the user inputs. --
Both of these queries display what I want them to display. In other words, the first query gives me all of the animals names in the table, and the second query gives me the synonyms for the word the user inputed.
At this point my problem is how to compare the synonyms to all the animals names. I've tried several queries with the LIKE command but I keep getting syntax errors.
Is what I am asking possible? If not what would be a better course of action? Any help would be greatly appreciated.
Thank You.
I got a semi fiddle going for y'all.
http://sqlfiddle.com/#!2/47d42/3
It only works for "bunny" since the entire synonym and word list is too big for fiddle.
select * from searchtestdb
where engname in
(
SELECT synonyms.synonym
FROM words
LEFT JOIN synonyms ON synonyms.word_id = words.word_id
WHERE word = "bunny"
)
SQLFIddle
EDIT: Since you probably also want to search for word directly inputted and not just it's synonyms, you should also add that condition:
OR engname = "bunny"
SQLFIddle
I think the idea is this: (pseudocoded)
Create a function which returns true or false (with a parameter as the search word) of whether there exists a result. This is a basic
SELECT COUNT > 0 FROM table WHERE text LIKE %parameter%
Now create a function that returns a table of results:
loop through the the synonyms of the word which again comes as a
parameter to this function
add to table of the results if a synonym in a loop fits the function above.
return the table

SSRS: How to select two or more values from a long filtered multiple selection list with different search strings

Let's consider a multiple selection parameter on a report: Employee
This parameter has a lot of possible values. Initially nothing is shown on the list and there is a textfield search parameter associated, that updates the Employee selection list with top n matches for the searched string.
If the entered search query is John Doe we can imagine that now the selection list shows:
John Doe
...
Xavier John Doesson
Now I can select as many items as I want from this filtered list, but if I want to select both John Doe and Alicia Keys happens the following:
First when I enter the search string "John Doe" the selection list gets populated accordingly
I select John Doe - OK
I enter search string "Alicia Keys", the selection list gets populated also
Selection of John Doe is gone - I want to be able to select both Alicia and John at the same time, but I don't want to go through a thousands of names long selection list
Update:
Forgot to mention that we have an OLAP cube in the background with dimension 'Employee'. This dimension is used as the source of the parameter and the param dataset uses MDX to fetch the values, therefore the SQL solution cannot be applied here.
The current solution creates an custom set with MDX Filter and Head functions and then this set is used in the ROWS-part of the MDX query.
Here is how the set created:
SET setEmployees AS {
HEAD(
FILTER( [Employees].[Employees].ALLMEMBERS,
INSTR([Employees].[Employees].CURRENTMEMBER.Name,#EmployeeSearch,1 >= 1 )
)
,100)
}
Basically the problem with this solution is that how do you add multiple search strings to the instr function
Is there a common solution to this kind of situation? Am I approaching the problem from wrong direction?
What you could do is make the search parameter more flexible, so you can handle input such as:
John OR Jane
If "OR" queries are more common than "AND" queries you could support it with queries such as:
John Jane
Note that this may throw people off, because the search features they're used to (such as Google search) typically tend interpret multiple words in the "AND" sense.
Anyhow, the tricky bit of course is the SQL behind the Employee data set. This should use the search parameter in a more flexible way. You haven't specified how that's currently working, but I imagine you may be using something like:
WHERE Employee.FullName LIKE '%' + #SearchParameter + '%'
You would need to extend that to support "OR" queries. There's a whole range of solutions for that, from quick 'n dirty handmade SQL (e.g. string split combined with WHERE...IN) to full-text querying. Choose a solution that's best for your situation.
If you have a fixed number of search terms than you can do something like the following.
FILTER( [Employees].[Employees].ALLMEMBERS,
INSTR([Employees].[Employees].CURRENTMEMBER.Name,#EmployeeSearch1,1 >= 1) OR
INSTR([Employees].[Employees].CURRENTMEMBER.Name,#EmployeeSearch2,1 >= 1)
)
Even if you can do that, I do not recommend it. You don't have the luxury to index Analysis Services like you do SQL. A better possible approach would be to query your data warehouse for the employees and return the appropriate keys, and then filter by those keys in your MDX statement.

Searching Mysql for similar string

People have different ideas of how to search for the same term.
For example Tri-Valley, Trivalley, Tri Valley (and possibly even incorrect spellings)
Currently that search is done like this
SELECT * FROM `table` WHERE `SchoolDistrict` LIKE '%tri valley%';
Is there an easy way to say 'space dash or no space' without writing out three like statements?
It seems like it could easily be done:
SELECT * FROM `table` WHERE `SchoolDistrict` LIKE '%tri%valley%';
But this only works if the initial input is 'tri-valley' or 'tri valley' If the initial input is 'trivalley' I have no idea where to place the % (theoretically that is, actually, I do, as we are only looking at about a dozen different school districts, but I'm looking to solve the larger problem)
You could consider using SOUNDEX, or SOUNDS LIKE if you have a lot of incorrect spellings. If you've got a lot of rows (or even if you don't), it might be wise to store the output of the SOUNDEX in an additional column.
I'd also recommend -- in the interests of accuracy -- introducing a separate table with an authoritative list of school districts, and run a query to find those which aren't in that list.
MySQL has a function called Sounds like.
link text
An alternative here is to recast the problem from search to select, if possible. Instead of letting your users enter free-form text to choose a school district, if you have a set of school districts generate a dropdown (or set of cascading dropdowns if the list is large, say by county, then by school district) and allow the user to select the appropriate one. Use this both for "searching" and for data entry to eliminate non-canonical entries. Obviously this only works when you can enumerate all of the entries.
Alternatively you could allow the user to choose a starts with or contains type search and simply generate the appropriate SQL ('tri%' or '%tri%') based on the selected search type. If the user understands that the search type is starts with or contains, they will likely adjust their search string until it yields the results they need.
The second statement you posted should do the trick:
SELECT * FROM 'table' WHERE 'SchoolDistrict' LIKE '%tri%valley%';
What you should do before you pass the search term into the select statement is to replace all characters and spaces with the % sign. For example,
SearchTerm = SearchTerm.Replace(" ","%");