4

我有两张这样的桌子,

表格1

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

表2

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

我需要在条件下内连接这两个表,如果表 2Locations中包含表 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应该是一个字符串。它不允许在那里给出列名。

我不能在查询中使用temptable或。variable因为此查询需要在一个名为的电子邮件活动工具上运行,该工具ExactTarget不支持temptablevariables

任何帮助将不胜感激。谢谢你。

4

3 回答 3

11

MySQL 5.5 的SQLFiddle 示例SQL的SQLFiddle 示例

表格和数据

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,因此不会出现不正确的结果。

于 2014-09-23T05:31:49.083 回答
1

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

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

SQL小提琴链接

于 2014-09-23T07:01:01.930 回答
0

我是 SQL 世界的新手,我遇到了这个确切的问题。实际上比这大得多,但这是获得我想要的东西的最后一块拼图。

这是我解决它的方法:

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

CONTAINS根据我们使用的语言使用。

想想我是多么接近放弃这个谜题,而解决方案实际上是多么简单。

于 2017-06-23T21:56:55.987 回答