繁体   English   中英

如何使用 SQL/mySQL 查询从表中查找相似项?

[英]How to find the similar items from tables using SQL/mySQL query?

如图所示,我有 2 个表。

我使用以下方法创建了表:

CREATE TABLE Table1(id varchar(50), country varchar(50));
insert into Table1(id, country) values("AA", "Belgium");
insert into Table1(id, country) values("AA", "Hungary");
insert into Table1(id, country) values("BB", "Germany");
insert into Table1(id, country) values("BB", "Canada");
insert into Table1(id, country) values("CC", "USA");
insert into Table1(id, country) values("DD", "Norway");
insert into Table1(id, country) values("DD", "Finland");
insert into Table1(id, country) values("DD", "France");

CREATE TABLE Table2(grpid varchar(50), country varchar(50));
insert into Table2(grpid, country) values("WWW", "Belgium");
insert into Table2(grpid, country) values("WWW", "Hungary");
insert into Table2(grpid, country) values("WWW", "Japan");
insert into Table2(grpid, country) values("YYY", "USA");
insert into Table2(grpid, country) values("ZZZ", "Norway");
insert into Table2(grpid, country) values("ZZZ", "Finland");
insert into Table2(grpid, country) values("ZZZ", "France");
insert into Table2(grpid, country) values("ZZZ", "Russia");

我需要以这种格式提取数据:

AA - 万维网

抄送 - YYYY

DD-ZZZ

逻辑是:

  1. 在表 1 中,AA 有比利时和匈牙利。 在表 2 中,WWW 也至少有比利时和匈牙利作为共同项。
  2. 在表 1 中,CC 有美国。 在表 2 中,YYY 也至少有 USA 作为共同项。
  3. 在表1中,DD有挪威、芬兰、法国。 在表2中,ZZZ至少还有挪威、芬兰、法国。

你能帮我解决我需要使用什么查询/逻辑来提取上述格式的数据吗? 这将是一个很大的帮助。 谢谢 :)

我认为这是一个join和一些聚合:

select t1.id, t2.grpid
from table1 t1 left join
     table2 t2
     on t1.country = t2.country
group by t1.id, t2.grpid
having count(*) = count(t2.country);   -- all in t1 match in t2

连接 2 个表:

select distinct t1.id, t2.grpid
from Table1 t1 inner join Table2 t2
on t2.country = t1.country

请参阅演示
结果:

| id  | grpid |
| --- | ----- |
| AA  | WWW   |
| CC  | YYY   |
| DD  | ZZZ   |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM