#113 ✓hold
Chris Wanstrath

empty? on associations

Reported by Chris Wanstrath | 2007-09-18 12:41:24 UTC

Nicolas wants:

class Provider < AR
 has_many :orders
end

class Order < AR
 belongs_to :provider
end

Provider.select { |p| p.name =~ 'A%' && p.orders.empty? }

(to retrieve all the providers which name begins by A and have no orders)

Mislav says:

SELECT ... FROM providers
LEFT JOIN orders ON provider.id = orders.provider_id
WHERE providers.name LIKE 'A%'
GROUP BY providers.id
HAVING COUNT(orders.id ) = 0

Comments and changes to this ticket

  • ronin-13570 (at lighthouseapp)

    ronin-13570 (at lighthouseapp) 2008-02-15 03:19:55 UTC

    Unfortunately this won't work as suggested as the GROUP BY clause MUST include every non aggregating column listed in the SELECT clause.

    Typically the same thing can be achieved using a correlated sub-query (and NOT EXIST) which most databases can optimise to essentially the same thing anyway.

  • Chris Wanstrath

    Chris Wanstrath 2008-02-16 03:30:58 UTC

    • State changed from “open” to “hold”

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

Shared Ticket Bins

People watching this ticket

Tags

Pages