1

i have some table like:
Sql Fiddle

I want this table to select only the following values(remove duplicates):
from | to
46 0
46 18
46 50
46 39
46 11
46 12
46 56

i use DISTINCT keyword,but this return folowing values:

46 0
46 18
46 50
46 39
46 11
11 46

46 12
46 56

please help me

user3077624
  • 125
  • 1
  • 4

2 Answers2

3
SELECT  DISTINCT a.*
FROM    TableName a
        INNER JOIN TableName b
          ON a.from = b.to
             AND a.to = b.from
WHERE   a.from < b.from
John Woo
  • 258,903
  • 69
  • 498
  • 492
1

Here is my solution, it seems not so ideal, but it works:

select distinct pm.`from`, pm.`to`
from `tsk_private_message` pm
left join
    (select distinct pm.`from`, pm.`to`
     from `tsk_private_message` pm
         inner join `tsk_private_message` pm2
         on (pm.`to` = pm2.`from`) and (pm2.`to` <> pm.`from`)) a
     using (`from`, `to`)
where a.`from` is null;

In this query I just search unnecessary rows among these conversations via subquery:

select distinct pm.`from`, pm.`to`
from `tsk_private_message` pm
    inner join `tsk_private_message` pm2
    on (pm.`to` = pm2.`from`) and (pm2.`to` <> pm.`from`)) a
using (`from`, `to`)

and "subtract" this result from main table.

Here is SQL Fiddle

Alexander Myshov
  • 2,881
  • 2
  • 20
  • 31