MySQL中两列的DISTINCT值

时间:2013-10-06 03:45:20

标签: php mysql sql database distinct

我有一张包含以下内容的表格:

+----+-----------+---------+--------+------+
| id | text_from | text_to |  text  | seen |
+----+-----------+---------+--------+------+
|  1 | A         | B       | Hello1 |    0 |
|  2 | X         | Y       | Hello2 |    1 |
|  3 | Y         | X       | Hello3 |    1 |
|  4 | B         | A       | Hello4 |    1 |
+----+-----------+---------+--------+------+

这是一个像A这样的对话,向B发送文本,B向A发送等等。如何进行DISTINCT对话?例如,A和B之间,或X和Y等之间的不同对话。

我希望得到像

这样的东西
+----+-----------+---------+--------+------+
| id | text_from | text_to |  text  | seen |
+----+-----------+---------+--------+------+
|  1 | A         | B       | Hello1 |    0 |
|  2 | X         | Y       | Hello2 |    1 |
+----+-----------+---------+--------+------+

如果text_from和text_to有两个唯一值,则无法重复。例如,如果有text_from = A,text_to = B,则表格不应该有text_from = B,text_to = A.

我正在为DISTINCT和GROUP BY尝试几种方法,因为几个小时,但无法找出任何解决方案!任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

似乎就像一个简单的NOT EXISTS应该做的伎俩。示例SQL Fiddle

select *
from table t
where not exists (
  select 1
  from table t1
  where
    (
      (t.text_from = t1.text_from
       and t.text_to = t1.text_to)
      or (t.text_from = t1.text_to
       and t.text_to = t1.text_from)
    ) and t.id > t1.id
  )