2013-07-05 77 views
5
USE tempdb 

CREATE TABLE A 
(
    id INT, 
    a_desc VARCHAR(100) 
) 

INSERT INTO A 
VALUES (1, 'vish'),(2,'hp'),(3,'IBM'),(4,'google') 

SELECT * FROM A 

CREATE TABLE B 
(
    id INT, 
    b_desc VARCHAR(100) 
) 

INSERT INTO B 
VALUES (1, 'IBM[SR4040][SR3939]'),(2,'hp[GR3939]') 

SELECT * FROM B 

SELECT * 
FROM A 
WHERE a_desc LIKE (SELECT b_desc FROM B) -- IN with LIKE problem here 

所有時間結束字符串在表B中都不相同所以我不能使用修剪方法來刪除特定字符並在In子句中匹配。使用[like]像在SQL中的子句?

- 上面扔錯誤子查詢返回的多個值

- 我只是舉例目的,我創建了這個例子

兩個表中1000行
--excepted output 
--IBM 
--hp 

--from一表

+1

有已經是幾個這樣的問題:http://stackoverflow.com/questions/15735117/using-like-and-in-and-a-subquery-in-a-single-sql-statement - HTTP://計算器。 COM /問題/ 10618912 /樣使用,子查詢 - 返回 - 多行 - http://stackoverflow.com/questions/2528858/with-sql-can-you-use-a-sub-query-in-a- where-like-clause –

回答

5

嘗試這一個 -

查詢:

SELECT * 
FROM A 
WHERE EXISTS(
    SELECT 1 
    FROM B 
    WHERE b_desc LIKE '%' + a_desc + '%' 
) 

輸出:

id   a_desc 
----------- ---------- 
2   hp 
3   IBM 

執行計劃:

proff

擴展統計:

stat

更新:

SELECT A.*, B.* 
FROM A 
OUTER APPLY (
    SELECT * 
    FROM B 
    WHERE b_desc LIKE '%' + a_desc + '%' 
) B 
WHERE b_desc IS NOT NULL 
+1

爲了更好地理解執行計劃,請閱讀以下簡短手冊:http://sqlmag.com/t-sql/understanding-query-plans – Devart

+0

是否有可能從列表B中的A列表中選擇列表? –

+1

請參閱最新的答案。 – Devart

3

你可以簡單的加入:

SELECT distinct a.* 
from A inner join b on b.b_desc like '%' + a.a_desc + '%' 
3

試試這個,這會給你確切的輸出

select distinct a.a_desc 
from A r 
join B b 
on b.b_desc like a.a_desc +'%' 
1
SELECT * 
FROM A , B 
WHERE a_desc LIKE '%' + b_desc + '%'