Suppose I have two tables:
CREATE TABLE `doctors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`clinic_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `clinics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
The next queries returns the same data but for large tables wich is better for performance?
-
Query with INNER JOIN
SELECT
doctors
.*
FROMdoctors
INNER JOINclinics
ONclinics
.id
=doctors
.clinic_id
WHEREclinics
.id
= 1; -
Query only with WHERE
SELECT
doctors
.*
FROMdoctors
WHEREdoctors
.clinic_id
= 1;
Best Answer
The second query. But why are you comparing them?
They may return the same data but they are answering two different questions. The first retrieves all records from
doctors
where a record exists inclinic
withid=1
. The second retrieves all records from doctors withclinic_id=1
regardless of whether a record exists inclinic
.In the absence of a foreign key constraint between the two tables, the queries are not comparable.