在包含条件的sql中内连接

Ano*_*shi 3 sql contains inner-join exacttarget

我有2张这样的桌子,

表格1

Id     Locations
--     ---------
1      India, Australia
2      US , UK 
Run Code Online (Sandbox Code Playgroud)

表2

Table2Id    Location
--------    --------
101         Italy
102         UK
103         Hungary
104         India
Run Code Online (Sandbox Code Playgroud)

我需要在条件内连接这两个表,如果Locations在table2中包含Locationtable1 中的 字段.结果就像

Id   Table2Id    Location     Locations
--   --------    --------     ---------
1     104        India        India, Australia
2     102        UK           US , UK 
Run Code Online (Sandbox Code Playgroud)

我试过类似的东西

Select t1.id,
       t2.Table2Id,
       t1.Locations,
       t2.Location
From Table1 t1 
Inner join Table2 t2 On CONTAINS(t1.Locations, t2.Location)
Run Code Online (Sandbox Code Playgroud)

但第二个参数contains应该是一个字符串.它不允许在那里给出列名.

我不能在查询中使用temptablevariable.因为此查询需要ExactTarget在不支持temptable和支持的电子邮件广告系列工具上运行variables.

任何帮助将受到高度赞赏.谢谢.

zed*_*xus 9

SQLFiddle例如为MySQL 5.5 SQLFiddle例如对于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');
Run Code Online (Sandbox Code Playgroud)

MySQL查询

select
  table1.id,
  table2.table2id,
  table2.location,
  table1.locations
from table1
join table2 on table1.locations like concat('%', table2.location, '%')
Run Code Online (Sandbox Code Playgroud)

SQL Server查询

select
  table1.id,
  table2.table2id,
  table2.location,
  table1.locations
from table1
join table2 on table1.locations like '%' + table2.location + '%'
Run Code Online (Sandbox Code Playgroud)

编辑

如果美国位置包含在国家/地区名称中,则上述查询可能无法按预期运行.要解决该问题,可以使用此查询

select
  table1.id,
  table2.table2id,
  table2.location,
  table1.locations
from table1
join table2 on 
  ',' + replace(table1.locations,', ', ',') + ',' like '%,' + table2.location + ',%'
Run Code Online (Sandbox Code Playgroud)

此查询强制India, Australia成为,India,Australia,.然后将其与之进行比较,,US,因此不会出现不正确的结果.