MySQL wildcard Like query with multiple words - mysql

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.

Related

SQL - How to search for a string that contains backslash

I'm trying to find all entries that contain a backslash anywhere, like so:
SELECT * FROM animals WHERE bodyType LIKE '%\\%'
I also tried:
SELECT * FROM animals WHERE bodyType LIKE '%\\\\%'
and
SELECT * FROM animals WHERE bodyType LIKE '%\\\\\\\\%'
Neither worked. Anyone know how to do this?
I am running the commands in MySQL Quick Admin v1.5.4
This question has not answer.
You try to match searching of content with backslash on names of columns.
Your (a bit general) query
SELECT * FROM tableName WHERE columnName LIKE '%\\%'
will give you any result if content of any column will contain backslash. In this case your query is correct. But you cannot match name of any column.
I looked into some books I have and all they say the same: this will select all records written in column of chosen name that are containing backslash. But columns have to be chosen exactly (they cannot be selected by name with using of SQL query).

Searching from a mysql database based on a string in php

I Have a string foo = "a,b". Now I want to search in the mysql database to get user_id while comparing the string to the likes field. The likes field has data in the format interest => a c v d b.
The different characters are seperated by a space. I tried Using like but the result was not upto the mark. How can I go about it?
This is my code
select user_id from users where interest like %foo%;
MySql does not support multiple keyword search in set like field, you should add OR condition of each search keyword with REGEXP
if your format interest like=> a,c,v,d,b then you can use FIND_IN_SET() function otherwise REGEXP provide to exact search.
SELECT user_id FROM users
WHERE interest REGEXP '[[:<:]]a[[:>:]]' AND interest REGEXP '[[:<:]]b[[:>:]]'
this query search only a and b in field not aa, bbax
LIKE does not support exact search.

SQL Text Search - EXACT before space, LIKE after in search term

I'm trying to create a SQL query which will supply values for auto completion for a text field. Everything is working however I can't seem to create an SQL query which is exact enough for the purposes I want. I am using MySQL.
If there is a space (or multiple spaces) in the search term, I only want the query to do a LIKE comparison on the part of the string after the last space.
For example, say I have two possible values in the database:
Bolt
Bolts Large
Currently if the user types 'Bolt' then a space, both values above are returned using this query -
SELECT name FROM items WHERE name LIKE 'SEARCH_TERM%'
What I want is that if the user types 'Bolt' then a space, then only Bolt is returned from the database.
Effectively meaning that only the last part of the search term after the space is compared using LIKE, the results should match exactly up until the last space.
I've also tried:
SELECT name FROM items WHERE name LIKE 'SEARCH_TERM[a-z]%'
But that actually returns no results using the above scenario.
Is what I'm after possible? I've also tried to explore using Full Text Search but have had no look with that. I believe full text search is enabled on the name field, however I have limited experience with this. The query below didn't work.
SELECT name FROM items WHERE MATCH(name) AGAINST('SEARCH_TERM')
Any advice or points would be very appreciated.
The query
SELECT name FROM items WHERE name LIKE 'Bolt %'
doesn't return any record, because both 'Bolt' and 'Bolts Large' don't match 'Bolt %'.
SELECT name FROM items WHERE name LIKE 'Bolt%'
returns both records, because both 'Bolt' and 'Bolts Large' match 'Bolt%'.
To look for 'Bolt' and not 'Bolts', you must add a space to both your search string and the column string:
SELECT name FROM items WHERE concat(name, ' ') LIKE 'Bolt %'
returns 'Bolt' but not 'Bolts Large'.
SELECT name FROM items WHERE REPLACE(name, ' ', '') LIKE 'SEARCH_TERM%'
You could also use CONCAT and TRIM, or just trim
SELECT name FROM items WHERE name LIKE TRIM('SEARCH_TERM')
or your choice
SELECT name FROM items WHERE name LIKE CONCAT(TRIM('SEARCH_TERM'), '%')
SELECT name FROM items WHERE name LIKE CONCAT('%',TRIM('SEARCH_TERM'))
SELECT name FROM items WHERE name LIKE CONCAT('%',TRIM('SEARCH_TERM'), '%')

Full JOIN MySQL Query is returning empty

So here is a MySQL Query:
SELECT TestSite . * , LoggedCarts . *
FROM TestSite, LoggedCarts
WHERE TestSite.email = 'LoggedCarts.Bill-Email'
LIMIT 0 , 30
It is returning an empty result set, when it should be returning four results based on the tables below.
First Table: LoggedCarts - Column: Bill-Email
casedilla#hotmail.com
crazyandy#theholeintheground.com
Second Table: TestSite - Column: email
samuel#lipsum.com
taco#flavoredkisses.com
honeybadger#dontcare.com
casedilla#hotmail.com
messingwith#sasquatch.com
The goal is to get a MySQL statement that returns the rows in Table: TestSite that don't match the rows in Table: LoggedCarts.
Note: I understand that the use of a hyphen in a column name requires special care when constructing a query, involving backticks to tell MySQL there are special characters. I would change the column names to match up, however the Table: LoggedCarts has data fed via post from a Yahoo Shopping Cart and without heavy preparation before insertion setting the name to anything but the key sent in the post data is daunting.
However, if it turns out rebuilding the data prior to insertion is easier than using a JOIN statement or for some reason using two columns with different names as the comparison columns just doesn't work, I will go through and rebuild the database and PHP code.
Single quotes indicate a string literal. You need to use backticks for identifiers. Also, each component of an identifier must be quoted individually.
SELECT TestSite . * , LoggedCarts . *
FROM TestSite, LoggedCarts
WHERE TestSite.email = LoggedCarts.`Bill-Email`
LIMIT 0 , 30
From the manual:
If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`.
With a bit of research inspired by somne of the hints given, I found the solution I was looking for here: SELECT * WHERE NOT EXISTS
Does exactly what I need it to do, and as a bonus, I like the shorthand syntax that is used that allows you to put in an alias for the table name and use the alias throughout the statement.
SELECT *
FROM TestSite e
WHERE NOT EXISTS
(
SELECT null
FROM LoggedCarts d
WHERE d.`Bill-Email` = e.email
)

mysql search for 's' ending should return the same without 's' ending

I want to search using MATCH in mysql.
I have 1 table contain "name" and "category" fields. the "category" field contain book,books,books.
what i want is, when i search "book" or "books" in category field, it should give me 3 row.
can anyone help me with this ?
thanks
i need to clarified this question, actually i have a website which have search field. when user input something on it, my web should search in category field. the real problem is, sometimes user input "book", sometimes "books", sometime "car" ,sometimes "cars". these "s" word after the word make me headache, i know that user really want is to find all related with book or car, so, what should i do, should i strip every "s" letter ? or is there any better solution ?
Ari
select *
from table
where category LIKE '%book%'
trim the user input to a acceptable length and try this query
$userInput = substr($input, 0, 4);
select * from table where category like "%$userInput%"
If you are running the query from PHP, for example, you could prepare the query there and then use a simple regular expression:
<?php
$term = 'book';
if(substr($term,-1) == 's') { //if term ends in an s
$term = substr($term,0,-1); //the word without the s
}
//TODO: escape $term to prevent SQL injection
$query = "
SELECT * FROM table
WHERE category REGEXP '{$term}s?' // s? matches zero or one 's' character
";
Searching with MATCH() requires a fulltext index on column category, which might be overkill.
If you really just want those two cases, you could write
select * from table where
category = 'book' or category = 'books'
With Oddant's answer you might also get results like 'probookcover' or whatever.
If you want it to be case insensitive you have multiple options.
select * from table where
lower(category) = 'book' or lower(category) = 'books'
or
select * from table where
category like 'book' or category like 'books'
Alternatively you could also do
select * from table where
category like 'book%'
which gets you all columns which start with book, but you might also get 'bookcover'.
EDIT: Considering your comment:
Like I said, match() is overkill, therefore I would do it like this:
select * from table where
category = whatYourUserEnters OR category = substring(whatYourUserEnters, 1, length(whatYourUserEnters) - 1)