I am trying to query in SQL and I can not resolve it.
I have a table tCliente
:
What I want to do is a JOIN with the same table to find each pair of clients that lives in the same city.
I try to do this:
SELECT DISTINCT c.codiClien, c.nombreClien, c1.codiClien, c1.nombreClien, c.ciudadClien
FROM tCliente c
INNER JOIN tCliente c1 ON c.ciudadClien = c1.ciudadClien
and get this:
But I should get this:
I know I have to filter data, but I have tried many things and I can not find the solution.
Also, I tried to use GROUP BY
but it is not possible. I wanted to group by pair, that is, something like this:
...
GROUP BY c.codiClien, c1.codiClien
But in doing so I get errors in the query. Could someone please help me? Thanks
Note:
When using ON
in the INNER JOIN
, I would like to know if it is "possible" to do that or should not do it, because the usual thing is to do tb1.id = tb2.id
The SELF JOIN in SQL, as its name implies, is used to join a table to itself. This means that each row in a table is joined to itself and every other row in that table. However, referencing the same table more than once within a single query will result in an error.
The self-join is a special kind of joins that allow you to join a table to itself using either LEFT JOIN or INNER JOIN clause. You use self-join to create a result set that joins the rows with the other rows within the same table.
As you may know, it is used to join and combine data from two or more tables into one common data set. In this article, I'm going to discuss special types of joins? in which you combine the same table twice—including joining a table to itself, also known as the self join.
Merging tables by columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins.
You must exclude itself on the inner join.
SELECT c.codiClien, c.nombreClien, c1.codiClien, c1.nombreClien, c.ciudadClien
FROM tCliente c
INNER JOIN tCliente c1
ON c.ciudadClien = c1.ciudadClien
AND c.codiClien < c1.codiClien;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With