Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL JOIN with the same table

I am trying to query in SQL and I can not resolve it. I have a table tCliente:

enter image description here

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:

enter image description here

But I should get this:

enter image description here

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

like image 825
Jonatan Lavado Avatar asked Jan 22 '17 17:01

Jonatan Lavado


People also ask

Can I join same table in SQL?

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.

Can I do a join in the same table?

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.

Can I join same table twice in SQL?

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.

How join columns to same table in SQL?

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.


1 Answers

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;
like image 108
McNets Avatar answered Oct 11 '22 19:10

McNets