需要根据使用'like'从多列中的选择返回来选择记录

时间:2014-08-20 16:07:59

标签: sql sql-server

我对T-SQL没问题,但我在这里努力解决我的问题。

我有一个查找表,根据搜索条件可以有一个或多个结果。 例如在这种情况下,Wimpole是搜索值:

select Location from L_Locations
where L_Locations.LocationID in
(
    select LocationID from [B_LocationsToMany
    where [B_LocationsToMany].NormalizedLocationID in
    (
        select [B_LocationsToMany].NormalizedLocationID 
        from [B_LocationsToMany] join L_Locations on [B_LocationsToMany].LocationID =     L_Locations.LocationID
        where L_Locations.Location like '%Wimpole%'
)

返回如下列表:

Wimpole
Wimpole Farm
Wimpole Hall
Wimpole Hole Fm
Wimpole land
Wimpole Lodge 
Wratworth & Wimpole

我需要搜索另一个表中的多个字段并返回任何这些字段包含上述任何值的结果。每个领域的操作员都需要是一个“类似”的类型。因为每个字段可以有0到2000个字符(即很多单词)。

一个起点将不胜感激。

好的,感谢Sam略微调整了他的建议并且让它正常工作

Select * 
    from CommonDocumentData
    where Location in
    (
        SELECT cdd.Location FROM L_Locations AS cdd
        JOIN
        (
            select Location from L_Locations
            where L_Locations.LocationID in
            (

            select LocationID from [B_LocationsToMany]
            where [B_LocationsToMany].NormalizedLocationID in
            (
                select [B_LocationsToMany].NormalizedLocationID 
                from [B_LocationsToMany] join L_Locations on [B_LocationsToMany].LocationID = L_Locations.LocationID
                where L_Locations.Location like '%Wimpole%'
            )
        )) as SearchResults

        ON CommonDocumentData.Description LIKE '%' + SearchResults.location + '%'
    )

2 个答案:

答案 0 :(得分:1)

你的查询应该是这样的。

 Select * 
    from secondtable
    where ID in (SELECT ID
        FROM secondtable
        JOIN (select Location from L_Locations
    where L_Locations.LocationID in
    (
        select LocationID from [B_LocationsToMany
        where [B_LocationsToMany].NormalizedLocationID in
        (
            select [B_LocationsToMany].NormalizedLocationID 
            from [B_LocationsToMany] join L_Locations on [B_LocationsToMany].LocationID =     L_Locations.LocationID
            where L_Locations.Location like '%Wimpole%'
    )
    ) as SearchResults
        ON secondtable.location LIKE '% ' + SearchResults.location + ' %'
    )

答案 1 :(得分:0)

这样的事情?

SELECT 
    *
FROM
    (SELECT 
        b.LocationID, b.NormalizedLocationID, Location
    FROM 
        B_LocationsToMany b INNER JOIN 
        L_Locations l ON 
        b.LocationID = l.LocationID INNER JOIN
        L_Locations s ON
        l.locationid = s.locationid
    WHERE 
        L.Location LIKE '%Wimpole%') l INNER JOIN
    TABLE t ON
    l.? = t.?
WHERE
    t.col1 = Location OR
    t.col2 = Location ...