How to find data that exists in multiple tables at the same time in mysql?

there are three class1,class2,class3 tables that represent three different classes. The structure of the table is the same, with two fields, name and birthday, indicating the student"s name and date of birth, respectively.

class1 data:

name    birthday
james   1999-12-12
emma    1999-10-29
tom     2000-01-12
paul    1999-09-30

class2 data:

name    birthday
tom     1997-01-09
john    1996-12-10
mike    1997-03-12
larry   1996-08-10

class3 data:

name    birthday
peter    1998-03-12
tom      1998-08-31
milly    1997-05-12
benjamin 1997-12-12

so how to find names that exist in three class at the same time. (here is tom. )

Apr.12,2022

select * from (class1 c1 join class2 c2 on c1.name=c2.name) join class3 c3 on c1.name=c3.name;

actual effect

(root)mytest-3306>>select c1.name c1name, c1.birthday c1birthday,
    -> c2.name c2name, c2.birthday c2birthday,
    -> c3.name c3name, c3.birthday c3birthday
    -> from (class1 c1 join class2 c2 on c1.name=c2.name)
    -> join class3 c3 on c1.name=c3.name;
+--------+---------------------+--------+---------------------+--------+---------------------+
| c1name | c1birthday          | c2name | c2birthday          | c3name | c3birthday          |
+--------+---------------------+--------+---------------------+--------+---------------------+
| tom    | 2000-01-12 00:00:00 | tom    | 1997-01-09 00:00:00 | tom    | 1998-08-31 00:00:00 |
+--------+---------------------+--------+---------------------+--------+---------------------+
1 row in set (0.00 sec)

this involves MySQL's multi-table federated query;

select a.name b.name as b_name from class2 as a,class3 as b where a.name=b.name

this is the simplest federated query of two tables. In case of a multi-table federated query, take another table class1 as the result of aQuery Calss2 and class3 as b to query the join tables again as follows, multiple tables and so on

select a.name from class1 as a,(select c.name,d.name as d_name from calss2 as c,class3 as d where c.name=d.name) as b where a.name=b.name

this is my suggestion. I don't know if it meets your requirements. If there is anything wrong, please point it out.

Menu