如何找到具有相同单词和相同主题的重复项?

时间:2018-10-25 17:14:47

标签: mysql

我有一个如下表。 表名称为“测试”。

+----+----------+----------+
| id | word     | topic    |
+----+----------+----------+
|  1 | plus     | math     |
|  2 | minus    | math     |
|  3 | multiple | math     |
|  4 | minus    | math     |
|  5 | cpu      | computer |
|  6 | click    | computer |
|  7 | monitor  | computer |
|  8 | cpu      | computer |
|  9 | multiple | computer |
+----+----------+----------+

如何找到相同主题的重复单词?

我想要下面的结果。

 +----+----------+----------+
 | id | word     | topic    |
 +----+----------+----------+
 |  2 | minus    | math     |
 |  4 | minus    | math     |
 |  5 | cpu      | computer |
 |  8 | cpu      | computer |
 +----+----------+----------+

3 个答案:

答案 0 :(得分:1)

select *
from your_table
where word in
(
    select word
    from your_table
    group by word, topic
    having count(*) > 1
)

答案 1 :(得分:0)

如果每个id都不需要单独的行,则可以执行以下操作:

select word, topic, group_concat(id)
from t
group by word, topic
having count(*) > 1

聚合可能会非常昂贵,因此如果您想要原始行,可以选择exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.word = t.word and t2.topic = t.topic and t2.id <> t.id
             );

为了提高性能,您希望在(word, topic, id)上建立索引。

答案 2 :(得分:0)

SELECT DISTINCT x.* 
          FROM test x 
          JOIN test y 
            ON y.id <> x.id 
           AND y.word = x.word 
           AND y.topic = x.topic;