1

I have a table having columns id and name

in my table 3 records present

id       name 
1        Chinmoy
2        Amit
3        Bhagi

I want result

name1     name2 
Amit      Bhagi
Amit      Chinmoy
Bhagi     chinmoy

I tried and succeeded up to this

name1    name2
Amit     Bhagi
Amit     Chinmoy
Bhagi    Amit
Bhagi    Chinmoy
Chinmoy  Amit
Chinmoy  Bhagi

by using this query

select tbl1.name,tbl2.name from test tbl1 
join test tbl1 on tbl1.name != tbl2.name
order by tbl1.name,tbl2.name;

Now i didn't get how to do.

I have to eliminate the record which are already present in opposite order.

Please Help

Thanks in advance

0

2 Answers 2

4

Basically, you can filter the result from the product of the two tables via a.Name < b.Name

SELECT  a.Name Name1, b.Name Name2
FROM    TableName a, TableName b
WHERE   a.Name < b.Name
ORDER   BY Name1, Name2

OUTPUT

╔═══════╦═════════╗
║ NAME1 ║  NAME2  ║
╠═══════╬═════════╣
║ Amit  ║ Bhagi   ║
║ Amit  ║ Chinmoy ║
║ Bhagi ║ Chinmoy ║
╚═══════╩═════════╝
Sign up to request clarification or add additional context in comments.

1 Comment

yes its working fine. can you please explain the query to me how a.Name < b.Name is working??
2

Try this:

select tbl1.name as n1, tbl2.name as n2 from test tbl1 
join test tbl2
on tbl1.name < tbl2.name
order by tbl1.name, tbl2.name;

Explanation:

You could add a condition tbl1.name < tbl2.name to eliminate duplicate values. This way you won't need the join condition you already have (tbl1.name != tbl2.name). Because when a < b, a is definitely not equal to b and also it sorts your names so that if Amit < Bhagi is true the opposite is not true and you won't also get Bhagi - Amit.

5 Comments

@user1926138 With your example given this answer fullfils the requirements. +1
@user1926138 it will give you exact same result. try it.
@tombom thanks for the edit, both where clause and on clause give the same result I'm not sure which one is the better practice.
Your join table where... is a raped ANSI-SQL standard. Either you have a ON clause when using JOIN or you build a cartesian product like FROM table1 t1, table2 t2 WHERE t1.id = t2.id. Do not mix both ways. But the former one, using explicit join syntax is the preferred one. It was introduced because the latter one was too error prone and is worse to read.
@user1926138 I added an explanation. Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.