簡體   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