Furze Furze - 6 months ago 17
PHP Question

How can I select all parent rows with a foreign key child row older than a certain date?

I have a table of orders and a table of updates, which are connected to orders by a one (order) to many (updates) relationship. I am trying to select all orders which have not been updated in the last 24 hours.

Here's the

updates
table (off the top of my head):

id INT PRIMARY KEY AUTO INCREMENT,
order_id INT NOT NULL ,
update VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
foreign key (order_id) REFERENCES orders(id)


And the
orders
table:

id INT PRIMARY KEY AUTO INCREMENT,
enabled TINYINT(1) NOT NULL DEFAULT 0,
reference VARCHAR(10) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP


How do I return all orders that are enabled, and which have either no update yet or the most recent update being older than one day? (It's fine for me to use either pure MySQL, or, preferably, Laravel's Eloquent ORM.)

Thank you.

Answer

I'd do a NOT EXISTS, to return orders that doesn't have a recent update:

select * from orders o
where enabled = 1
  and not exists (select 1 from updates u
                  where u.order_id = o.id
                    and u.created_at >= NOW() - INTERVAL 1 DAY)
Comments