Sql Server Full Text Search Single Result Column Searched Across Multiple Columns - sql

I am trying to implement an AutoComplete search box(like google) using SQL Server 2008 and Full Text Search.
Say I have 3 columns that I want to search across and have created the proper indexes and what not.
The columns are ProductName, ProductNumber, and Color...
For the user input I want to search for possible matches across all three columns and suggest the proper search term.
So say the user starts typing "Bl"
id like to return a single column containtng results like "Black" "Blue" which come from the Color column and also any matches from the other two columns(like ProductNumber: BL2300)
So basically I need to search across multiple columns and return a single column as the result. Is there a way to do this?

UPDATED follwoing comment of op If you created a FULLTEXT INDEX on different columns, then you can simple use CONTAINS or FREETEXT to look on one of them, all of them, or some of them. Like this:
SELECT *
FROM YourTable
WHERE CONTAINS(*, #SearchTerm);
If you want to look on all the columns that are included in the FULLTEXT INDEX. or:
SELECT *
FROM YourTable
WHERE CONTAINS((ProductName, ProductNumber, Color), #SearchTerm);
If you want to specify the columns that you want to search.
If you need the results in one column, you are gonna have to do a UNION and do a search for every column you want to be searched.
SELECT *
FROM YourTable
WHERE CONTAINS(ProductName, #SearchTerm)
UNION
SELECT *
FROM YourTable
WHERE CONTAINS(ProductNumber, #SearchTerm)
UNION
SELECT *
FROM YourTable
WHERE CONTAINS(Color, #SearchTerm)

If you do not need to associate the single columns, something like
SELECT * FROM Table WHERE ProductName LIKE #SearchTerm + '%'
UNION
SELECT * FROM Table WHERE ProductNumber LIKE #SearchTerm + '%'
UNION
SELECT * FROM Table WHERE Color LIKE #SearchTerm + '%'
is a good point to start from.

Related

How to search multiple values in a column with contains?

I have a list with searchitems:
DROP TABLE IF EXISTS #searchitems
SELECT 'Road' as item
INTO #searchitems
UNION
SELECT 'Bike'
item
Road
Bike
And I want looking for rows that contain that items
I put a Full Text Index on the Name column and I tried this already
SELECT Name
FROM [AdventureWorksLT2019].[SalesLT].[Product]
WHERE CONTAINS(*, (Select item FROM #searchitems) )
But it does not work. With just one value its working but not with a list of search values.
Does it even possible with CONTAINS on a SQL-Server.
I expect something like this:
SELECT distinct Name
FROM [AdventureWorksLT2019].[SalesLT].[Product]
WHERE CONTAINS(*, 'Road OR Bike' )
expected output, but why its not working on a input list
Refere the documentation https://learn.microsoft.com/fr-fr/sql/t-sql/queries/contains-transact-sql?view=sql-server-ver16
SELECT distinct Name
FROM [AdventureWorksLT2019].[SalesLT].[Product]
WHERE CONTAINS(*, 'Road OR Bike' )
Is working, official example:
SELECT Name
FROM Production.Product
WHERE CONTAINS(Name, ' Mountain OR Road ')
Update
maybe that's your solution :
SELECT Name
FROM [AdventureWorksLT2019].[SalesLT].[Product]
WHERE CONTAINS(*, (Select STRING_AGG(item, ' OR ') FROM #searchitems)
One way is to use a CTE and JOIN it to your table with LIKE:
WITH searchitems AS
(SELECT 'Road' AS item
UNION ALL
SELECT 'Bike')
SELECT DISTINCT y.name
FROM yourtable y
JOIN searchitems s
ON y.name LIKE CONCAT('%',s.item,'%');
In the CTE, you can select as many items as desired.
You should generally note that lots of LIKE conditions can slow down your query if your table holds very many entries (and of course, similar ideas like CONTAINS can be very slow, too).
This should be avoided if possible and be replaced with an exact string search to improve the execution time.
Then of course the way shown above is no more required, you could just use a standard IN clause:
SELECT name
FROM yourtable
WHERE
name IN ('Road','Bike','Hello World','Another Text');
Try out with some sample data: db<>fiddle

SQL: Return records containing a word where the last letter is anything except K

Suppose I have a table containing a column by the name "Query". I have to display the records where the string in this column has used noloc instead of nolock. Note that noloc can be followed/preceded by ) or space etc. I just need all records that have anything before and after noloc except nolock. Is there a way to do it in SQL?
I tried:
select * from table1
where Query LIKE '%noloc%'
but this includes queries containing nolock. I tried variations of the above like putting space before and/or after % but none of them fills all the criteria.
You can use both conditions in the where clause
select * from table1
where Query LIKE '%noloc%' and Query NOT LIKE '%nolock%'
You want anything + noloc + any one char but k + anything. Here:
select * from table1
where Query LIKE '%noloc[^k]%'

TSQL Select where one column equals another column

I'm trying to create a search based on where items go together in the same table.
So if I input a value like a123 for column BoxNo then all values in the column Goeswith which are also a123 are selected. This below code is my attempt, but does not work.
SELECT *
FROM Equipment
WHERE (BoxNo LIKE '%') = GoesWith
thanks
If you want all rows where BoxNo and GoesWith have the same value then it's this:
SELECT *
FROM Equipment
WHERE BoxNo = GoesWith
Maybe you mean,
SELECT *
FROM tableName
WHERE 'a123' IN (BoxNo, GoesWith)
or maybe this,
SELECT *
FROM tableName
WHERE BoxNo LIKE '%a123%' AND
BoxNo = GoesWith
If you want to search all items like a123 in BoxNo column:
SELECT * From Equipment WHERE BoxNo LIKE '%a123%'
Of if you want to search for a123 in both columns:
DECLARE #Search Varchar(50) = 'a123'
SELECT * From Equipment WHERE BoxNo = #Search AND GoesWith = #Search
I suspect you meant 'as well as', hence OR:
select * from equipment where BoxNo='a123' OR GoesWith='a123'
Be a bit careful to add bracketing if you need some further constraints adding...
Were you looking for a general match of all Box records that have another entry that they "go with"?
if so then you need an self-join (which uses aliases to identify the records):
select
b.BoxNo,
g.GoesWith
from
equipment as b
inner join equipment as g on b.BoxNo = g.GoesWith
This identifies all the records that have a matching box (and which thing they go with).
Change to a left join to include records that have no match.
It will produce multiple matches if a Box has several GoesWith entries, but by returning either DISTINCT b.* or DISTINCT g.* you can get a list of individual matches.

SQL Server Full-Text-Search FREETEXTTABLE search multiple columns

I'm using the below query to return results from a table using Full-Text-Search.
In SQL2000 it was only possible to search one or all columns in a table. Is it possible in SQL 2008?
I would like to search two tables, Problem and Solution (Both indexed and in the same table):
DECLARE #topRank int set #topRank=(SELECT MAX(RANK)
FROM FREETEXTTABLE([Support_Calls], Problem, 'test', 1))
SELECT [ID] AS [Call No],Company_Name, Problem, Solution, CONVERT(VARCHAR(20),CAST((CAST(ftt.RANK as DECIMAL)/#topRank * 100) AS DECIMAL(13,0))) + '%' as Match
FROM [Support_Calls] INNER JOIN FREETEXTTABLE([Support_Calls], Problem, 'test') as ftt ON ftt.[KEY]=[ID] ORDER BY ftt.RANK DESC;
From what I can see the FREETEXTTABLE does not accept more than one column?
You specify them in parentheses; FREETEXTTABLE(tablename, (col1,col2,col3), 'expr') or use an asterisk to seach all columns in the index.
From MSDN,
Returns a table of zero, one, or more rows for those columns containing character-based data types for values that match the meaning, but not the exact wording, of the text in the specified freetext_string. FREETEXTTABLE can only be referenced in the FROM clause of a SELECT statement like a regular table name.
Queries using FREETEXTTABLE specify freetext-type full-text queries that return a relevance ranking value (RANK) and full-text key (KEY) for each row.
They give the following syntax:
FREETEXTTABLE (table , { column_name | (column_list) | * }
,'freetext_string'
[ , LANGUAGE language_term ]
[ ,top_n_by_rank ] )
So yes, what Alex K. said as well.
If you created a FULLTEXT INDEX on different columns, then you can simple use CONTAINS or FREETEXT to look on one of them, all of them, or some of them. Like this:
SELECT *
FROM YourTable
WHERE CONTAINS(*, #SearchTerm);
If you want to look on all the columns that are included in the FULLTEXT INDEX. or:
SELECT *
FROM YourTable
WHERE CONTAINS((ProductName, ProductNumber, Color), #SearchTerm);
If you want to specify the columns that you want to search. If you need the results in one column, you are gonna have to do a UNION and do a search for every column you want to be searched.
SELECT *
FROM YourTable
WHERE CONTAINS(ProductName, #SearchTerm)
UNION
SELECT *
FROM YourTable
WHERE CONTAINS(ProductNumber, #SearchTerm)
UNION
SELECT *
FROM YourTable
WHERE CONTAINS(Color, #SearchTerm)

How to search multiple columns in MySQL?

I'm trying to make a search feature that will search multiple columns to find a keyword based match. This query:
SELECT title FROM pages LIKE %$query%;
works only for searching one column, I noticed separating column names with commas results in an error. So is it possible to search multiple columns in mysql?
If it is just for searching then you may be able to use CONCATENATE_WS.
This would allow wild card searching.
There may be performance issues depending on the size of the table.
SELECT *
FROM pages
WHERE CONCAT_WS('', column1, column2, column3) LIKE '%keyword%'
You can use the AND or OR operators, depending on what you want the search to return.
SELECT title FROM pages WHERE my_col LIKE %$param1% AND another_col LIKE %$param2%;
Both clauses have to match for a record to be returned. Alternatively:
SELECT title FROM pages WHERE my_col LIKE %$param1% OR another_col LIKE %$param2%;
If either clause matches then the record will be returned.
For more about what you can do with MySQL SELECT queries, try the documentation.
If your table is MyISAM:
SELECT *
FROM pages
WHERE MATCH(title, content) AGAINST ('keyword' IN BOOLEAN MODE)
This will be much faster if you create a FULLTEXT index on your columns:
CREATE FULLTEXT INDEX fx_pages_title_content ON pages (title, content)
, but will work even without the index.
1)
select *
from employee em
where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';
2)
select *
from employee em
where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';
First is usefull when we have data like : 'firstname lastname'.
e.g
parth patel
parth p
patel parth
Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.
e.g
parth-patel
parth_p
patel#parth
Here is a query which you can use to search for anything in from your database as a search result ,
SELECT * FROM tbl_customer
WHERE CustomerName LIKE '%".$search."%'
OR Address LIKE '%".$search."%'
OR City LIKE '%".$search."%'
OR PostalCode LIKE '%".$search."%'
OR Country LIKE '%".$search."%'
Using this code will help you search in for multiple columns easily
SELECT * FROM persons WHERE (`LastName` LIKE 'r%') OR (`FirstName` LIKE 'a%');
Please try with above query.