2014-09-23 60 views
2

我有2代表這樣,內加入與含有條件

表1

Id  Locations 
--  --------- 
1  India, Australia 
2  US , UK 

表2

Table2Id Location 
-------- -------- 
101   Italy 
102   UK 
103   Hungary 
104   India 

我需要內部連接這兩個表在條件下,如果表2中的Locations包含表1中的Location字段。其結果就會像

Id Table2Id Location  Locations 
-- -------- --------  --------- 
1  104  India  India, Australia 
2  102  UK   US , UK 

我想是這樣

Select t1.id, 
     t2.Table2Id, 
     t1.Locations, 
     t2.Location 
From Table1 t1 
Inner join Table2 t2 On CONTAINS(t1.Locations, t2.Location) 

contains第二個參數應該是一個字符串。它不允許在那裏提供列名。

我不能在查詢中使用temptablevariable。由於此查詢需要在名爲ExactTarget的電子郵件營銷活動工具上運行,因此不支持temptablevariables

任何幫助將不勝感激。謝謝。

回答

7

SQLFiddle example爲MySQL 5.5 SQLFiddle example爲SQL

表和數據

create table table1 (id int, locations varchar(100)); 
insert into table1 values 
(1, 'India, Australia'), 
(2, 'US, UK'); 

create table table2 (table2id int, location varchar(100)); 
insert into table2 values 
(101, 'Italy'), 
(102, 'UK'), 
(103, 'Hungary'), 
(104, 'India'); 

MySQL查詢

select 
    table1.id, 
    table2.table2id, 
    table2.location, 
    table1.locations 
from table1 
join table2 on table1.locations like concat('%', table2.location, '%') 

SQL Server查詢

select 
    table1.id, 
    table2.table2id, 
    table2.location, 
    table1.locations 
from table1 
join table2 on table1.locations like '%' + table2.location + '%' 

編輯

在情況下美國的位置被包含在國名澳大利亞,根據需要將上面的查詢可能無法正常工作。要解決這個問題,這裏使用

select 
    table1.id, 
    table2.table2id, 
    table2.location, 
    table1.locations 
from table1 
join table2 on 
    ',' + replace(table1.locations,', ', ',') + ',' like '%,' + table2.location + ',%' 

這個查詢勢力India, Australia成爲,India,Australia,一個可能的查詢。然後將它與,US,進行比較,因此不會遭受不正確的結果。

+1

您的查詢無法正常工作,請參閱:http://sqlfiddle.com/#!3/90a6b/1 – Rimas 2014-09-23 05:38:26

+1

@Rimas好眼睛。 '','+在聯接中替換(table1.locations,',',',')+','like'%,'+ table2.location +',%''可能看起來很難看,但可能會訣竅 – zedfoxus 2014-09-23 05:46:54

+0

@zfus非常感謝你的答案.. – 2014-09-23 05:50:48

1

如果你正在使用MySQL,你可以看看下面的選項: INSTR

select table2id, location, table1.id, locations 
from table2 inner join table1 on instr(locations,location) >= 1; 

SQL Fiddle Link

0

我是新來的SQL世界,我面對這個確切的問題。實際上比這更大,但這是獲得我想要的最後一塊難題。

這裏是我如何解決它:

SELECT * FROM t1 CROSS JOIN t2 
WHERE t1.Locations CONTAINS t2.Location; 

根據我們所使用的語言使用CONTAINS

思考我放棄這個難題有多接近,以及解決方案的真實性有多簡單。