TSQL Select where one column equals another column - sql

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.

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

Select Rows from 1 table with multiple criteria

I'm trying to select rows from my table where I look at the DocumentNo and Description, and if the Description repeats, it gets neglected / tossed / looked over. This is in MS Access, but can switch to DBeaver if necessary.
My table is of the sort
DocumentNo Description
SSPT284886 Tongs
SSPT284894 Kit
SSPT284894 Tongs
SSPT284895 Tubing
SSPT284895 Tubing
SSPT284895 Countertop
In this case, my query should return everything except the 5th line.
I've tried
Select *
FROM Table1
WHERE Table1.DocumentNo <> Table1.DocumentNo AND Table1.Description <> Table1.Description;
But this yields nothing, as I assume it looks for values that aren't equal to itself, essentially.
I think you simply want SELECT DISTINCT:
select distinct DocumentNo, Description
from table1;

Using CONTAINS to find items IN a table

I'm trying to write a SP that will allow users to search on multiple name strings, but supports LIKE functionality. For example, the user's input might be a string 'Scorsese, Kaurismaki, Tarkovsky'. I use a split function to turn that string into a table var, with one column, as follows:
part
------
Scorsese
Kaurismaki
Tarkovsky
Then, normally I would return any values from my table matching any of these values in my table var, with an IN statement:
select * from myTable where lastName IN (select * from #myTableVar)
However, this only returns exact matches, and I need to return partial matches. I'm looking for something like this, but that would actually compile:
select * from myTable where CONTAINS(lastName, select * from #myTableVar)
I've found other questions where it's made clear that you can't combine LIKE and IN, and it's recommended to use CONTAINS. My specific question is, is it possible to combine CONTAINS with a table list of values, as above? If so, what would that syntax look like? If not, any other workarounds to achieve my goal?
I'm using SQL Server 2016, if it makes any difference.
You can use EXISTS
SELECT * FROM myTable M
WHERE
EXISTS( SELECT * FROM #myTableVar V WHERE M.lastName like '%'+ V.part +'%' )
Can your parser built the entire statement? Will that get you what you want?
select *
from myTable
where CONTAINS
(lastName,
'"Scorsese" OR "Kaurismaki" OR "Tarkovsky"'
)
This can be done using CHARINDEX function combined with EXISTS:
select *
from myTable mt
where exists(select 1 from #myTableVar
where charindex(mt.lastName, part) > 0
or charindex(part, mt.lastName) > 0)
You might want to omit one of the conditions in the inner query, but I think this is what you want.

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

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.

Is there any way to combine IN with LIKE in an SQL statement?

I am trying to find a way, if possible, to use IN and LIKE together. What I want to accomplish is putting a subquery that pulls up a list of data into an IN statement. The problem is the list of data contains wildcards. Is there any way to do this?
Just something I was curious on.
Example of data in the 2 tables
Parent table
ID Office_Code Employee_Name
1 GG234 Tom
2 GG654 Bill
3 PQ123 Chris
Second table
ID Code_Wildcard
1 GG%
2 PQ%
Clarifying note (via third-party)
Since I'm seeing several responses which don't seems to address what Ziltoid asks, I thought I try clarifying what I think he means.
In SQL, "WHERE col IN (1,2,3)" is roughly the equivalent of "WHERE col = 1 OR col = 2 OR col = 3".
He's looking for something which I'll pseudo-code as
WHERE col IN_LIKE ('A%', 'TH%E', '%C')
which would be roughly the equivalent of
WHERE col LIKE 'A%' OR col LIKE 'TH%E' OR col LIKE '%C'
The Regex answers seem to come closest; the rest seem way off the mark.
I'm not sure which database you're using, but with Oracle you could accomplish something equivalent by aliasing your subquery in the FROM clause rather than using it in an IN clause. Using your example:
select p.*
from
(select code_wildcard
from second
where id = 1) s
join parent p
on p.office_code like s.code_wildcard
In MySQL, use REGEXP:
WHERE field1 REGEXP('(value1)|(value2)|(value3)')
Same in Oracle:
WHERE REGEXP_LIKE(field1, '(value1)|(value2)|(value3)')
Do you mean somethign like:
select * FROM table where column IN (
SELECT column from table where column like '%%'
)
Really this should be written like:
SELECT * FROM table where column like '%%'
Using a sub select query is really beneficial when you have to pull records based on a set of logic that you won't want in the main query.
something like:
SELECT * FROM TableA WHERE TableA_IdColumn IN
(
SELECT TableA_IdColumn FROM TableB WHERE TableA_IDColumn like '%%'
)
update to question:
You can't combine an IN statement with a like statement:
You'll have to do three different like statements to search on the various wildcards.
You could use a LIKE statement to obtain a list of IDs and then use that in the IN statement.
But you can't directly combine IN and LIKE.
Perhaps something like this?
SELECT DISTINCT
my_column
FROM
My_Table T
INNER JOIN My_List_Of_Value V ON
T.my_column LIKE '%' + V.search_value + '%'
In this example I've used a table with the values for simplicity, but you could easily change that to a subquery. If you have a large list (like tens of thousands) then performance might be rough.
select *
from parent
where exists( select *
from second
where office_code like trim( code_wildcard ) );
Trim code_wildcard just in case it has trailing blanks.
You could do the Like part in a subquery perhaps?
Select * From TableA Where X in (Select A from TableB where B Like '%123%')
tsql has the contains statement for a full-text-search enabled table.
CONTAINS(Description, '"sea*" OR "bread*"')
If I'm reading the question correctly, we want all Parent rows that have an Office_code that matches any Code_Wildcard in the "Second" table.
In Oracle, at least, this query achieves that:
SELECT *
FROM parent, second
WHERE office_code LIKE code_wildcard;
Am I missing something?