SQL Like with a subquery
Asked Answered
L

5

27

How can i make this work?

SELECT * 
FROM   item 
WHERE  item_name LIKE '%' 
                      || (SELECT equipment_type 
                          FROM   equipment_type 
                          GROUP  BY equipment_type) 
                      || '%' 

The inner sub query returns a list of strings like 'The' 'test' 'another' and i want to select all items from the item table where the item_name is similar to the sub queries return values. I need to have the wild cards.

Is there an alternative where i can use wildcards but use the IN sql command instead?

Lues answered 18/6, 2013 at 19:57 Comment(3)
Don't you have ID to do this??Haggis
@Haggis What do you mean?Lues
@Haggis i specifically stated that i have a list of strings i want to compare item_name to.Lues
C
40

You can use an INNER JOIN:

SELECT I.* 
FROM item I
INNER JOIN (SELECT equipment_type 
            FROM equipment_type 
            GROUP BY equipment_type) E
    ON I.item_name LIKE '%' || E.equipment_type || '%'
Chantellechanter answered 18/6, 2013 at 20:3 Comment(3)
ahhh nice nice, i will try this and let you know ASAP. tyLues
For those using SQL Server... The double pipes appears to be the ANSI-SQL standard but won't work in T-SQL. #23373050Entrance
Note that this solution produces duplicates.Philosophism
K
13

If you don't want to worry about duplicates and don't care which one matches, then switch to using exists:

select i.*
from item i
where exists (select 1
              from equipment_type
              where i.item_name like '%'||equipment_type||'%'
             )
Keratoplasty answered 18/6, 2013 at 20:6 Comment(0)
I
4

For MSSql Server above does not fly

Use

select *
from item I
where exists (select 1
          from equipment_type
          where i.item_name like (SELECT CONCAT('%',equipment_type,'%')) 
         )
Ignacia answered 30/6, 2020 at 11:49 Comment(0)
D
4

You can use CONCAT and insert the subquery:

SELECT * FROM item WHERE  item_name LIKE  
CONCAT('%', (
    SELECT equipment_type
    FROM equipment_type
    GROUP BY equipment_type), '%'
)
Divalent answered 29/7, 2021 at 12:26 Comment(0)
C
0
SELECT * 
FROM   item 
WHERE  item_name LIKE ANY  
                      (SELECT '%'|| equipment_type || '%' 
                          FROM   equipment_type 
                          GROUP  BY equipment_type)
Choochoo answered 25/1 at 15:29 Comment(2)
Please explain the effect of what you propose and why it helps to solve the problem. Try for How to Answer.Xenophobe
In addition to @Yunnosch’s question, this question already has a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.Feinleib

© 2022 - 2024 — McMap. All rights reserved.