如何查看字符串是否包含列中的值?

时间:2017-03-24 14:16:41

标签: sql sql-server string sql-server-2012 substring

所以我想说我有两张桌子。一个有字符串,一个有值。

第一个名为Strings

的表格
  | StringField
1 | Hello, World!
2 | I have got
3 | A lovely bunch of coconuts

第二个名为Values的表:

  | ValueField
1 | bart
2 | Hello
3 | 3gs
4 | foop
5 | nch of

SELECT * FROM Strings
WHERE StringField --contains a value from ValueField in Values

在上面的查询中,我想要从Strings表中返回第1行和第3行,因为第1行包含“Hello”而第3行包含“unch of”。

4 个答案:

答案 0 :(得分:3)

您可以使用INNER JOIN

SELECT DISTINCT Id, StringField
FROM dbo.Strings s
INNER JOIN dbo.[Values] v
    ON s.StringField LIKE '%' + v.ValueField + '%'
;

答案 1 :(得分:2)

的PostgreSQL

SELECT strings.* 
FROM strings
INNER JOIN (
    SELECT upper('%' || valuefield || '%') AS pattern
    FROM values 
    WHERE id = 4
) AS valuespattern ON (valuespattern.pattern like upper(strings.stringfield))

的SQLserver

SELECT Strings.* 
FROM Strings
INNER JOIN (
    SELECT upper('%' + ValueField + '%') AS pattern
    FROM Values 
    WHERE id = 4
) AS ValuesPattern ON (ValuesPattern.pattern like upper(Strings.StringField))

答案 2 :(得分:1)

Select S.StringField
from Strings as S
Join Values as V
on S.StringField like '%' + V.ValueField + '%'

答案 3 :(得分:1)

;WITH cte_Strings
As
(   
SELECT 1 ID, 'Hello, World!' AS StringField  Union All
SELECT 2, 'I have got'                       Union All
SELECT 3, 'A lovely bunch of coconuts'
),cte_Values
As
(
SELECT 1 Id, 'bart' As ValueField   Union All
SELECT 2, 'Hello'                   Union All
SELECT 3, '3gs'                     Union All
SELECT 4, 'foop'                    Union All
SELECT 5, 'nch of'
)
SELECT  Distinct c1.* 
FROM cte_Strings c1
INNER JOIN cte_Values c2
ON CHARINDEX(c2.ValueField,c1.StringField)>0