I'm trying to query a like statement across multiple columns. I have the following search terms:
'dog'
'cat'
'rabbit'
'gerbil'
'guinea pig'
'hamster'
and I need search for these terms or terms LIKE these in the 'animals' table which has about 40 different columns. I am aware I can do the like statement by doing
Select * from animals where [animalscolumn] like ('%dog%') or like ('%cat%') or like ('%gerbil%') or like ('%hamster%') or like ('%guinea pig%')
However the 'animalscolumn' isn't the only column I need to run the 'LIKE' statement across. I have to search for these terms in about 40 columns. Would anyone happen to know how? Thanks!
multiple like statements can not be used with or directly. You have to use column name for each like statement.
Use multiple like as mentioned below.
Select *
from animals
where
(
[animalscolumn] like ('%dog%') or
[animalscolumn] like ('%cat%') or
[animalscolumn] like ('%gerbil%') or
[animalscolumn] like ('%hamster%') or
[animalscolumn] like ('%guinea pig%')
)
If you want to find a set of number you can use IN
SELECT *
FROM tableName
WHERE columnId IN (154,156,133,157,119)
$sql = "SELECT * from like1 WHERE tutorial_author LIKE '$apply'
OR
tutorial_title LIKE '$apply'";
if($mode == 'search_contact'){
// $prefix='%';
$apply=$dataObj['search'];
$data = array();
// $sql = "SELECT * from add_contact WHERE tutorial_author OR tutorial_title LIKE '$apply'";
$sql = "SELECT * from add_contact WHERE
first_name LIKE '%$apply%'
OR
last_name LIKE '%$apply%'
OR
title LIKE '%$apply%'
OR
company LIKE '%$apply%'
OR
address LIKE '%$apply%'";
$result = $myConnection->query($sql);
if ($result->num_rows > 0) {
// print_r($result->fetch_assoc());
while($row = $result->fetch_assoc()) {
$row['user_image'] = site_url.upload_dir.$row['image'];
// print_r($row);
$data[]=$row;
}
$array = array('status'=>true, 'message'=> 'contacts fetched successfully', 'data'=> $data);
echo json_encode($array);
exit;
} else {
$array = array('status'=>false, 'message'=> "No contacts available" );
echo json_encode($array);
exit;
}
}
Select * from cscart_users
where status like '%a' and user_type like '%c' and firstname like '%az%';
Select * from cscart_users where status like '%a' and user_type like '%c'and firstname like'%az%';
syntax:
select * from tablename where columnname like'%b' and columnname2 like '%g';
Here is an example of a SQL Server stored procedure that takes a parameter.
CREATE PROCEDURE [dbo].sp_SearchMultiple #SearchTerm nvarchar(256)
AS
BEGIN
SET #SearchTerm = '%' + #SearchTerm + '%'
SELECT TOP 100
id, col1, col2, col3
FROM
asset_f
WHERE
col1 LIKE #SearchTerm OR col2 LIKE #SearchTerm OR col3 LIKE #SearchTerm
ORDER BY
id ASC
END
Related
I am trying to pull data based on multiple keywords from the same column.
Currently I have a SQL statement that works like this.
SELECT *
FROM Customers
WHERE CustomerName LIKE 'a%'
OR CustomerName LIKE '_r%'
OR CustomerName LIKE 'si%';
That works fine. What I am trying to achieve is to pass the keywords c("a", "_r", "si") as a vector. Like this:
keywords <- c("a", "_r", "si")
SELECT *
FROM Customers
WHERE CustomerName LIKE '%' + keywords + '%';
That did not work. How do I submit a variable with a bunch of keywords into the like statement?
Use sprintf and paste/collapse= . Within a sprintf format %s is replaced with the next argument and %% means %.
keywords <- c("a", "_r", "si")
sql <- keywords |>
sprintf(fmt = "CustomerName LIKE '%%%s%%'") |>
paste(collapse = " OR \n") |>
sprintf(fmt = "SELECT *
FROM Customers
WHERE %s")
cat(sql, "\n")
giving:
SELECT *
FROM Customers
WHERE CustomerName LIKE '%a%' OR
CustomerName LIKE '%_r%' OR
CustomerName LIKE '%si%'
Just another option using string_split() and a JOIN
Example
DECLARE #Find VARCHAR(max) = ('a%,_r%,si%')
Select Distinct A.*
From Customers A
Join string_split(#Find,',') B
on CustomerName like B.value
I am getting array from front end to perform filters according that inside the SQL query.
I want to apply a LIKE filter on the array. How to add an array inside LIKE function?
I am using Angular with Html as front end and Node as back end.
Array being passed in from the front end:
[ "Sports", "Life", "Relationship", ...]
SQL query is :
SELECT *
FROM Skills
WHERE Description LIKE ('%Sports%')
SELECT *
FROM Skills
WHERE Description LIKE ('%Life%')
SELECT *
FROM Skills
WHERE Description LIKE ('%Relationship%')
But I am getting an array from the front end - how to create a query for this?
In SQL Server 2017 you can use OPENJSON to consume the JSON string as-is:
SELECT *
FROM skills
WHERE EXISTS (
SELECT 1
FROM OPENJSON('["Sports", "Life", "Relationship"]', '$') AS j
WHERE skills.description LIKE '%' + j.value + '%'
)
Demo on db<>fiddle
As an example, for SQL Server 2016+ and STRING_SPLIT():
DECLARE #Str NVARCHAR(100) = N'mast;mode'
SELECT name FROM sys.databases sd
INNER JOIN STRING_SPLIT(#Str, N';') val ON sd.name LIKE N'%' + val.value + N'%'
-- returns:
name
------
master
model
Worth to mention that input data to be strictly controlled, since such way can lead to SQL Injection attack
As the alternative and more safer and simpler approach: SQL can be generated on an app side this way:
Select * from Skills
WHERE (
Description Like '%Sports%'
OR Description Like '%Life%'
OR Description Like '%Life%'
)
A simple map()-call on the words array will allow you to generate the corresponding queries, which you can then execute (with or without joining them first into a single string).
Demo:
var words = ["Sports", "Life", "Relationship"];
var template = "Select * From Skills Where Description Like ('%{0}%')";
var queries = words.map(word => template.replace('{0}', word));
var combinedQuery = queries.join("\r\n");
console.log(queries);
console.log(combinedQuery);
Have query with parentesis:
SELECT *
FROM users
WHERE company_id = 1 AND (
name LIKE "%smith%" OR
last_name LIKE "%smith%"
)
But in codeigniter have:
$query_members = $this->db
->select('users.*')
->from('users')
->like(array('users.names' => $search))
->or_like(array('users.last_name' => $search))
->where(array('users.company_id' => 1));
This generate:
SELECT *
FROM users
WHERE
name LIKE '%smith%' OR
last_name LIKE '%smith%' AND
company_id = 1;
And does not works, i need ((a or b) and c), not (a or b and c). I found solution here: Codeigniter parentheses in dynamic Active Record query but the variable is escaped with full quotes, i need escape with "%" pre and pos value. I have this:
$search_escaped = $this->db->escape($search);
$query_members = $this->db
->select('users.*')
->from('users')
->where('(users.names LIKE "%'.$search_escaped.'%" OR users.last_name LIKE "%'.$search_escaped.'%")')
->where(array('members.company_id' => (int)$company_id));
But the query add bad quotes:
SELECT `users`.*
FROM `users`
WHERE (users.names LIKE "%'smith'%" OR users.last_name LIKE "%'smith'%")
AND `members`.`company_id` = 2
The "%'smith'%" is bad quoted. How I can solve this by using active record of codeigniter 3.0.0?
hello I am trying to achieve something like this
should give results if
where 'Robert Doug' like '%Robert'
or
where 'Robert Doug' like '%Doug Robert'
if users enters first name or last name and if it matches in that whole string it should return the record.
Any help is appreciated.
Try like this
SELECT * FROM [YOUR TABLE_NAME] WHERE [COLUMN_NAME] LIKE ('%'+[USER PROMPT]+'%')
Or try this..
SELECT PATINDEX('%Robert%',NAME_COLUMN)
FROM [YOUR TABLE_NAME]
Or..
SELECT NAME_COLUMN
FROM [YOUR TABLE_NAME]
WHERE PATINDEX('%Robert%',NAME_COLUMN)<>'0'
Thank you all i tried something like this
WHERE
( d_searchJobTitle.term like '%'+case when CHARINDEX(' ','implementation analyst') >0 then SUBSTRING('implementation analyst',1,CHARINDEX(' ','implementation analyst')) else 'implementation analyst' end+'%'
and
d_searchJobTitle.term like '%'+ case when CHARINDEX(' ','implementation analyst') >0 then SUBSTRING('implementation analyst',CHARINDEX(' ','implementation analyst'),len('implementation analyst'))
else 'implementation analyst' end
+'%' )
Basically, what I need is the inverse of this:
SELECT * FROM `table` WHERE `query` LIKE '%string%'
Something that looks like:
SELECT * FROM `table` WHERE '%string%' LIKE 'thestringmachine'
I looked up the internet an operation called CONTAINS() but it doesn't seem to work.
Can someone help me?
Edit:
$inc = "themachinethatthinks";
$query = mysql_query("SELECT * FROM `spell` WHERE CONTAINS('$inc',`word`)");
$num = mysql_numrows($query); $i=0;
while ($i < $num) {
$val = mysql_result($query,$i,"word");
echo $val."<br>";
$i++;
}
The database contains lot of words (only).
I am not sure I understand what you need, but I try:
SELECT * FROM your_table
WHERE LOCATE(your_col, 'thestringmachine') > 0
If you need query to be case insensitive:
SELECT * FROM your_table
WHERE LOCATE(LOWER(your_col), LOWER('thestringmachine')) > 0
I cannot try it, 'cause I don't have a SQL DB here at hand, but try this
SELECT * FROM `tablename` WHERE `thethinkingmachine' LIKE CONCAT('%', `colname`, '%');
If this would work, I doubt it will be very performant.