sql中包含条件的内部联接

sql中包含条件的内部联接,sql,inner-join,contains,exacttarget,Sql,Inner Join,Contains,Exacttarget,我有两张这样的桌子 表1 Id Locations -- --------- 1 India, Australia 2 US , UK 表2 Table2Id Location -------- -------- 101 Italy 102 UK 103 Hungary 104 India 如果表2中的Locations包含表1中的Location字段,我需要在条件下对这两个表进

我有两张这样的桌子

表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)
但是
包含的第二个参数应该是字符串。这里不允许给出列名

我不能在查询中使用
tentable
variable
。因为此查询需要在名为
ExactTarget
的电子邮件活动工具上运行,该工具不支持
Attentiable
变量

我们将非常感谢您的帮助。谢谢。

对于MySQL 5.5 对于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, '%')
select
  table1.id,
  table2.table2id,
  table2.location,
  table1.locations
from table1
join table2 on table1.locations like '%' + table2.location + '%'
SQL Server查询

select
  table1.id,
  table2.table2id,
  table2.location,
  table1.locations
from table1
join table2 on table1.locations like concat('%', table2.location, '%')
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 + ',%'

此查询强制
印度、澳大利亚
变为
、印度、澳大利亚
。然后将其与
、美国、
进行比较,因此不会出现不正确的结果。

如果您使用的是Mysql,您可以查看以下选项:


我是SQL世界的新手,我面临的正是这个问题。实际上比这个大得多,但这是我想要的最后一块拼图

我是这样解决的:

SELECT * FROM t1 CROSS JOIN t2
WHERE t1.Locations CONTAINS t2.Location;
根据我们使用的语言使用
包含的


想想我是多么接近于放弃这个难题,而解决方案又是多么简单。

@Rimas good eye<联接中的代码>'、'+replace(table1.locations、'、'、')+'、'类似'%、'+table2.location+'、%'
可能看起来很难看,但可能会执行以下操作:trick@AnoopJoshi不客气。希望您可以根据自己的需要调整此查询