[英]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.
我正在尝试选择过去24小时内未更新的所有订单。
Here's the updates
table (off the top of my head): 这是
updates
表(不在我的头上):
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: 和
orders
表:
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.)
(对我来说,可以使用纯MySQL,或者最好使用Laravel的Eloquent ORM。)
Thank you. 谢谢。
I'd do a NOT EXISTS
, to return orders that doesn't have a recent update: 我会执行
NOT EXISTS
,以返回没有最新更新的订单:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.