sql - Selecting unique values from self-referencing table -
suppose have following data in table named my_tabel
:
╔═══════════╦═════════════╦════════════╗ ║ id ║ person_name ║ partner_id ║ ╠═══════════╬═════════════╬════════════╬ ║ 101 ║ john ║ 3 ║ ║ 100 ║ miller ║ 0 ║ ║ 3 ║ ruby ║ 101 ║ ║ 180 ║ jack ║ 0 ║ ║ 199 ║ george ║ 65 ║ ║ 23 ║ joseph ║ 0 ║ ║ 34 ║ fredrick ║ 117 ║ ║ 117 ║ jinan ║ 34 ║ ║ 122 ║ verena ║ 0 ║ ║ 65 ║ mary ║ 199 ║ ╚═══════════╩═════════════╩════════════╝
where 0 values in partner_id column indicates he/she single.
we need display partnered persons without repeating or duplication, desired result should like:
╔═════════════╦══════════════╗ ║ person_name ║ partner_name ║ ╠═════════════╬══════════════╬ ║ john ║ ruby ║ ║ george ║ mary ║ ║ fredrick ║ jinan ║ ╚═════════════╩══════════════╝
what best sql query returns above results?
i'm using code:
select t1.name, t2.name my_tabel t1 inner join my_tabel t2 on (t2.id = t1.partner_id)
but returned result is:
╔═════════════╦══════════════╗ ║ person_name ║ partner_name ║ ╠═════════════╬══════════════╬ ║ john ║ ruby ║ ║ ruby ║ john ║ ║ george ║ mary ║ ║ mary ║ george ║ ║ fredrick ║ jinan ║ ║ jinan ║ fredrick ║ ╚═════════════╩══════════════╝
how sql statement should updated (or replaced another) desired results?
just add condition 1 side of each pair:
select t1.name, t2.name my_table t1 inner join my_table t2 on (t2.id = t1.partner_id) t1.id < t2.id;
Comments
Post a Comment