A
A
amvero2017-06-22 21:55:41
MySQL
amvero, 2017-06-22 21:55:41

How to find records with the same fields?

Hello!
There is a table of the form:
ID | Category | Field1 | .... | FieldN
In it, ID is the primary key auto-increment, Category is a certain string, the remaining fields contain some data.
For each Category, there are >=1 records that have at least a data field that is unique (within the category). I.e:

ID | Category | Field1 | ... | FieldN
1 | category1 | somedata | ... | somedata
2 | category1 | otherdata | ... | somedata
3 | category1 | somedata | ... | otherdata 
4 | category2 | otherdata | ... | somedata 
5 | category3 | somedata | ... | somedata
6 | category4 | unique data | ... | unique data

Required: for category x, find all categories that have the same data in the same column. That is, in the example above, for category4 there will be no such records, for the other three there will be two others.
Dirty it would look like this:
-- получим все возможные варианты полей в первой категории
SELECT `Field1`, ...,  `FieldN` FROM `table` WHERE `Category`='category1'

-- найдём все категории, у которых поля совпадают, и которые не являются первой категорией
SELECT `Category` FROM `table` 
WHERE ( `Field1` IN ( соответствующий столбец из первого запроса )
OR `FieldN` IN ( ... ) ) 
AND `Category`!='category1'

Can this query be made better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Boris Korobkov, 2017-06-22
@BorisKorobkov

Somehow everything is confusing with the fields. For understanding, it is better to indicate real data.
Option 1.
If I understand correctly, it is enough to find duplicate values

SELECT Field1 
FROM MyTable 
GROUP BY Field1 
HAVING COUNT(*) > 1

and then records on them
SELECT * 
FROM MyTable 
WHERE  Field1 = ...

Option 2.
SELECT * 
FROM MyTable MyTable1, MyTable MyTable2 
WHERE  MyTable1.Field1 = MyTable2.Field1 AND MyTable1.Category != MyTable2.Category

F
Fortop, 2017-06-22
@Fortop

Try the next option.
Didn't check the database.

SELECT t1. category, t2.category
FROM table as t1
JOIN table as t2 ON t1.Field1=t2.Field1
OR t1.Field2=t2.Field2
....
OR t1.FieldN = t2.FieldN

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question