Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql self-join table remove duplicate lines

Tags:

I have the following table:

╔════════╦════════════╗ ║ USERID ║ LANGUAGEID ║ ╠════════╬════════════╣ ║      1 ║          2 ║ ║      1 ║          7 ║ ║      1 ║          8 ║ ║      2 ║         10 ║ ║      2 ║          3 ║ ╚════════╩════════════╝ 

now I want to create all the possible pairs of languages for each user which means that I want the result set to be: for user 1: (2,7), (7,8), (2,8)

for user 2: (10,3)

to do so I've done the following query:

SELECT a.userId , a.LanguageId, b.LanguageId FROM knownlanguages a, knownlanguages b   WHERE a.userID=b.userID   AND a.LanguageId<>b.LanguageId 

the result that i'm getting is for user 1: (2,7), (7,8), (2,8) , (7,2), (8,7), (8,2)

for user 2: (10,3), (3,10)

there is no difference for me between (10,3) and (3,10)

how can I remove the duplicate lines?

tnx

like image 660
Shai Zarzewski Avatar asked Jan 13 '13 15:01

Shai Zarzewski


People also ask

How do you delete duplicate rows in SQL using self join?

Solution. Select column values in a specific order within rows to make rows with duplicate sets of values identical. Then you can use SELECT DISTINCT to remove duplicates. Alternatively, retrieve rows in such a way that near-duplicates are not even selected.

How do you avoid duplicates in SQL join?

ALWAYS put the join predicates in the join. Where clause predicates are not evaluated until after the entire result set has been generated, so unneeded rows are carried along throughout the processing, and in certain outer join scenarios, putting predicates in where clause will generate incorrect results.

How can I delete duplicate rows in SQL table?

To delete the duplicate rows from the table in SQL Server, you follow these steps: Find duplicate rows using GROUP BY clause or ROW_NUMBER() function. Use DELETE statement to remove the duplicate rows.

How do you find duplicate records using self join in SQL?

Check for Duplicates in Multiple Tables With INNER JOINUse the INNER JOIN function to find duplicates that exist in multiple tables. Sample syntax for an INNER JOIN function looks like this: SELECT column_name FROM table1 INNER JOIN table2 ON table1. column_name = table2.


1 Answers

With your identifiers:

SELECT a.userId , a.LanguageId, b.LanguageId   FROM knownlanguages a inner join knownlanguages b       on a.userID=b.userID and a.LanguageId < b.LanguageId 

Testing: Fot table:

create table t ( u int, l int);  insert into t values  (    1,               2), (    1,               7), (    1,               8), (    2,               10), (    2,               3); 

The query is:

select t1.u, t1.l as l1, t2.l as l2 from t t1 inner join t t2    on t1.u = t2.u and t1.l < t2.l 

( Results)

like image 117
dani herrera Avatar answered Nov 05 '22 19:11

dani herrera