You use one table twice in a query, giving it two names, for example.
Aliases are often entered with the keyword AS. You also usually specify a join condition (without it, you get a Cartesian product of a table connected to itself). For preference, you use the explicit JOIN notation.
SELECT c1.id AS sender, c2.id AS replier FROM contacts AS c1 JOIN contacts AS c2 ON c1.xxx = c2.yyy;
It is not clear which columns can be used for joining in this example; we have no information to help solve this problem.
As a rule, another table should be used as an intermediary, for example, a message table:
SELECT c1.id AS sender, c1.email AS sender_email, c2.id AS replier, c2.email AS replier_email, m.date_time FROM messages AS m JOIN contacts AS c1 ON m.sender_id = c1.id JOIN contacts AS c2 ON m.replier_id = c2.id;
Jonathan leffler
source share