![](/img/trans.png)
[英]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.