[英]How to JOIN a group of tables in a database with similar name using SQL query?
[英]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
邏輯是:
你能幫我解決我需要使用什么查詢/邏輯來提取上述格式的數據嗎? 這將是一個很大的幫助。 謝謝 :)
我認為這是一個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.