简体   繁体   English

如何选择外键子行早于特定日期的所有父行?

[英]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.

相关问题 日期比昨天晚,我如何突出显示一行 - how can i highlight a row when date is older than yesterday Laravel 删除所有早于某个日期的目录 - Laravel delete all directories that are older than a certain date 外键“无法添加或更新子行” - Foreign Key “can not add or update a child row” 一个父行,另一个表中的多个子行。 如何将它们全部排成一排? - One parent row, multiple child rows in another table. How to get them all in one row? Laravel检查超过特定日期的文章 - Laravel checking articles older than a certain date 子表中的外键如何自动获取其在父表中实际拥有的值 - How foreign key in a child table, can automatically get the value it actually has in the parent table 选择到外键列:无法添加或更新子行:外键约束失败 - select to foreign key column: Cannot add or update a child row: a foreign key constraint fails Doctrine (Symfony) 中的外键。 如何将新孩子绑定到已经存在的父母? - Foreign Key in Doctrine (Symfony). How do I bind a new child to an already existing parent? 如何将子 arrays 迭代为父数组的“行”,同时(按名称)在每个“行”中回显值(键/值对) - How to iterate child arrays as “rows” of parent array, while (by name) echoing values (of key/value pairs) in each “row” 在mysql中选择比当前日期更早的行 - selecting rows that are older than current date in mysql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM