Search code examples
mysqlsql-like

How can I show duplicate rows using MySQL "LIKE"?


I have table with following structure and test records:

+--------+--------+---------+
| vid    | number | name    |
+--------+--------+---------+
| 2      | 012345 | name1   | r1
| 6      | 0012345| 1name   | r2
| 5      | 012345 | namee   | r3
| 6      | 9111522| name6   | r4
| 3      | 999999 | name65  | r5
| 2      | 0999999| name64  | r6
+--------+--------+---------+

The rows r1, r2 and r3 are duplicated, because 12345 is inside in the field number and r5 and r6 are duplicated. I want to show duplicate rows from this table.

What query I must to create to get this result?

Thanks in advance !


Solution

  • It looks like you're storing your "number" column as a string (VARCHAR). If that is the case I'd highly recommend you switch it to an INT column type. If that's not possible then I'd make sure your app normalises the data on the way in so the string-formatted numbers are always in the same format. It will make life much easier.

    Anyway in terms of the data that's there, assuming that a duplicate means "the numeric representations of the data are the same" then this would work

    SELECT
      t1.vid, t1.number, t1.name
    FROM table t1
      INNER JOIN table t2
      ON CAST(t1.number AS SIGNED)=CAST(t2.number AS SIGNED) AND t1.vid!=t2.vid
    GROUP BY t1.vid