I have two tables with date_created
columns and a foreign key relation:
CREATE TABLE `parent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date_created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`date_created` datetime NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`)
) ENGINE=InnoDB;
I need to fetch only the parents whose children all have a date_created
of less than January of this year.
My first thought was to use the distinct parent_id
from all children matching this criteria:
select distinct parent_id
from child
where date_created < '2015-01-01'
Problem is, this also returns parents with children outside the criteria:
select id, date_created
from child
where parent_id in (
select distinct parent_id
from child
where date_created < '2015-01-01'
) and date_created >= '2015-01-01'
-- 22 rows returned