Get all duplicate records in table

Slow variant:

SELECT *
FROM table t1
WHERE t1.domain_id = 1569
AND t1.is_active = 1
AND (t1.field IN (SELECT t2.field
				 FROM table t2
				 WHERE t2.is_active = 1
				 GROUP BY t2.field
				 HAVING COUNT(t2.field) > 1))

Faster variant:

SELECT l0_.*
FROM table l0_
inner join table n2 on n2.field = l0_.field
where l0_.id <> n2.id
AND l0_.is_active = 1
Group By l0_.id

QueryBuilder:

$queryBuilder
	->innerJoin(Table::class,'table', Query\Expr\Join::WITH, 'entity.field = table.field')
	->andWhere('entity.id <> table.id')
	->andWhere('table.isActive = 1')
	->groupBy('entity.id')
;

Problem with NULL values you should remember

When trying to execute SELECT OR UPDATE query for rows different than a specific value, we should be aware to insert additional statement for null values too.

For Example:

        UPDATE account_event 
        SET account_event.assigned_to_id = 2 
        WHERE account_event.status != 1

With this query your goal is to update all rows where account_event.status is different from 1. But if status have null value it wont be updated!
In MySQL all null elements are skipped from comparison and will never be Selected or Updated.

When you have a null fields you should always add additional statement for null like this:

        UPDATE account_event 
        SET account_event.assigned_to_id = 2 
        WHERE account_event.status != 1 
        OR account_event.status IS NULL

MySQL Foreign Keys

A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

* If you want to use foreign key all your tables should be with InnoDB engine.

Foreign Key on create table

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Continue reading “MySQL Foreign Keys”