过滤相同或相似的列值

时间:2018-11-29 13:54:20

标签: mysql sql

我有一个如下表:

ID | Title
_____________________
1  | Samurai
2  | Airplane
3  | Samurai (2nd edition)
4  | The Deer Hunter
5  | Samurai
6  | Pan's Labyrinth
7  | Airplane 2010

我只需要保留具有相同或相似记录的记录。上表的预期结果如下:

ID | Title
_____________________
1  | Samurai
2  | Airplane
3  | Samurai (2nd edition)
5  | Samurai
7  | Airplane 2010

这可以通过一个或至少两个查询来实现吗?

2 个答案:

答案 0 :(得分:3)

一种方法是在第一个表中的标题是第二个表中标题的子字符串的情况下进行自联接,反之亦然:

SELECT DISTINCT t1.ID, t1.Title
FROM yourTable t1
INNER JOIN yourTable t2
    ON (t1.Title LIKE CONCAT('%', t2.Title, '%') OR
       t2.Title LIKE CONCAT('%', t1.Title, '%')) AND
       t1.ID <> t2.ID
ORDER BY
    t1.ID;

enter image description here

Demo

此处必须使用DISTINCT进行选择,因为一对给定的匹配记录将在结果集中出现两次。意识到这是有效的,因为例如一个标题Samurai作为标题Samurai (2nd edition)的一部分出现。其他匹配也适用类似的逻辑。

根据戈登的评论进行编辑:

SELECT t1.ID, t1.Title
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2
              WHERE (t1.Title LIKE CONCAT('%', t2.Title, '%') OR
                     t2.Title LIKE CONCAT('%', t1.Title, '%')) AND
                    t1.ID <> t2.ID)
ORDER BY
    t1.ID;

Demo

答案 1 :(得分:-1)

SELECT MIN(ID) AS ID, Title
from table
group by Title

GROUP BY文档https://www.w3schools.com/sql/sql_groupby.asp