J
J
JackShcherbakov2018-03-10 20:17:55
SQL
JackShcherbakov, 2018-03-10 20:17:55

How to get rid of logical error in SQL query?

Hello! There is a database with customers. I want to understand which customers live in the same city. Decided to use a left join.
Here is the request itself:

Select C1.Name, C2.Name, C1.City 
 FROM Customers AS C1, Customers AS C2   
 WHERE C1.City = C2.City        
              AND C1.Name <> C2.Name    
 ORDER BY C1.Name DESC;

Here is the output:
+---------------------------------+---------------------------------+------------------+
| Name                            | Name                            | City             |
+---------------------------------+---------------------------------+------------------+
| Евгений Щербаков                | Олег Щербаков                   | Saint Petersburg |
| Олег Щербаков                   | Евгений Щербаков                | Saint Petersburg |
+---------------------------------+---------------------------------+------------------+

As you can see, the lines are, in fact, duplicated. How to avoid it? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bedward70, 2018-03-10
@JackShcherbakov

As an idea: notice "<>" on "<". Total:

Select C1.Name, C2.Name, C1.City 
 FROM Customers AS C1, Customers AS C2   
 WHERE C1.City = C2.City        
              AND C1.Name < C2.Name    
 ORDER BY C1.Name DESC;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question