MySql self join predicate not understanding how it works -
i learning self joins , have simple table:
+-----------+-------------+ | name | location | +-----------+-------------+ | robert | guadalajara | | manuel | guadalajara | | dalia | guadalajara | | alejandra | guadalajara | | luis | guadalajara | | monica | guadalajara | | claudia | guadalajara | | scartlet | guadalajara | | sergio | guadalajara | | rick | mexico city | | rene | mexico city | | ramon | culiacan | | junior | culiacan | | kasandra | culiacan | | emma | culiacan | | johnatha | dunedin | | miriam | largo | | julie | largo | +-----------+-------------+
what intended find people share same location 'robert'.
using self joins saw following works reading solutions on here but, don't understand going on , not able explain if asked me how worked:
select users1.name users users1, users users2 users1.location = users2.location , users2.name = 'robert';
correctly returns following result:
+-----------+ | name | +-----------+ | robert | | manuel | | dalia | | alejandra | | luis | | monica | | claudia | | scartlet | | sergio | +-----------+
what don't understand how and users2.name = 'robert'
plays role in returning correct result.
can explain step step how mysql processes table expression , predicate:
where users1.location = users2.location , users2.name = 'robert';
to return correct result.
i prefer use explicit syntax in self-join makes easier see joining 2 tables (or table in case):
select u2.name users u1 inner join users u2 on u1.location = u2.location u1.name = 'robert'
a picture worth thousand words, here temporary table created in above query looks like:
+-----------+-------------+-----------+-------------+ | u1.name | u1.location | u2.name | u2.location | +-----------+-------------+-----------+-------------+ | robert | guadalajara | robert | guadalajara | | robert | guadalajara | manuel | guadalajara | | robert | guadalajara | dalia | guadalajara | | robert | guadalajara | alejandra | guadalajara | | robert | guadalajara | luis | guadalajara | | robert | guadalajara | monica | guadalajara | | robert | guadalajara | claudia | guadalajara | | robert | guadalajara | scarlet | guadalajara | | robert | guadalajara | sergio | guadalajara | +-----------+-------------+-----------+-------------+
the query joins each location on first users
table each matching location in second users
table. where
clause restricts users named 'robert'
in first table.
Comments
Post a Comment