检索相关记录数量最少的记录

发布于 2024-09-29 13:49:49 字数 382 浏览 2 评论 0原文

Property 和Reservation 之间存在一对二多的关系。酒店有名为“nr_of_bookings”的列。我需要 DQL 来仅检索 COUNT(Reservation) 小于 Property.nr_of_bookins 的属性。

示例:某些房产的 nr_of_bookings = 3 。如果它有 5 个相关预订,则不会被检索。但如果它有 2 个相关的预订,则会将其检索。

我尝试了多种组合,但我显然错过了一些东西。我发布了类似的问题 此处,但最好从头开始。谢谢。

There is one-2-many relation between Property and Reservation. Property has column called 'nr_of_bookings'. I need DQL that will retrieve only the properties that has COUNT(Reservation) less than Property.nr_of_bookins.

An example: Some Property has nr_of_bookings = 3 . If it has 5 Reservations related, it will not be retrieved. But if it has 2 related Reservations, it will be retrieved.

I tried numerous combinations, but I miss something obviosly. I posted similar question
here , but it is better to start from scratch. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清晨说晚安 2024-10-06 13:49:49

您是否尝试过:

'SELECT p FROM Product p WHERE SIZE(p.reservations) < p.nr_of_bookings'

编辑:以上适用于 Doctrine 2。对于 Doctrine 1.2,查看您的代码,我猜您的 HAVING 子句引用的内容不在 group by 或 a 的结果中聚合函数。尝试如下操作:

$q = PropertyTable::getInstance()
    ->createQuery('p') 
    ->select('p.*, COUNT(r.id) as num_of_reservations, SUM(p.nr_of_bookings) as num_bookings') 
    ->leftJoin('p.Reservation r') 
    ->groupBy('p.id') 
    ->having('num_of_reservations < num_bookings');

您按 p.id 进行分组,因此 SUM(p.nr_of_bookings) 将等于 p.nr_bookings

来自 MySQL 文档:

SQL 标准不允许 HAVING 子句命名任何未在 GROUP BY 子句中找到的列(如果该列未包含在聚合函数中)。

Have you tried:

'SELECT p FROM Product p WHERE SIZE(p.reservations) < p.nr_of_bookings'

EDIT: The above is for Doctrine 2. For Doctrine 1.2, looking at your code, I'm guessing your HAVING clause is referencing something that's not in a group by or the result of an aggregate function. Try something like this:

$q = PropertyTable::getInstance()
    ->createQuery('p') 
    ->select('p.*, COUNT(r.id) as num_of_reservations, SUM(p.nr_of_bookings) as num_bookings') 
    ->leftJoin('p.Reservation r') 
    ->groupBy('p.id') 
    ->having('num_of_reservations < num_bookings');

You're grouping by p.id so SUM(p.nr_of_bookings) will be equal to p.nr_bookings.

From the MySQL documentation:

The SQL standard does not permit the HAVING clause to name any column not found in the GROUP BY clause if it is not enclosed in an aggregate function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文