Find records which assoicated records do not belong to certain record

glizda101

In my system I have a following structure:

class Worker
  has_many :worker_memberships
end

class WorkerMembership
  belongs_to :worker
  belongs_to :event
end

class Event
  has_many :worker_memberships
end

Imagine I have a certain @event. How can I find all workers that have NO worker_memberships belonging to this @event?

D-side

This is pretty much synthesis of both other answers.

First: stick to has_many through as @TheChamp suggests. You're probably using it already, just forgot to write it, otherwise it just wouldn't work. Well, you've been warned.

I generally do my best to avoid raw SQL in my queries whatsoever. The hint about select I provided above produces a working solution, but does some unneessary stuff, such as join when there's no practical need for it. So, let's avoid poking an association. Not this time.

Here comes the reason why I prefer has_many through to has_and_belongs_to_many in many-to-many associations: we can query the join model itself without raw SQL:

WorkerMembership.select(:worker_id).where(event: @event)

It's not the result yet, but it gets us the list of worker_ids we don't want. Then we just wrap this query into a "give me all but these guys":

Worker.where.not(id: <...> )

So the final query is:

Worker.where.not(id: WorkerMembership.select(:worker_id).where(event: @event) )

And it outputs a single query (on @event with id equal to 1):

SELECT `workers`.* FROM `workers` WHERE (`workers`.`id` NOT IN (SELECT `worker_memberships`.`worker_id` FROM `worker_memberships` WHERE `worker_memberships`.`event_id` = 1))

I also give credit to @apneadiving for his solution and a hint about mysql2's explain. SQLite's explain is horrible! My solution, if I read the explain's result correctly, is as performant as @apneadiving's.

@TheChamp also provided performance costs for all answers' queries. Check out the comments for a comparison.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Select records that are not associated with the other record

분류에서Dev

SQL query to find unreferenced records

분류에서Dev

How do I loop through certain records, check a query, and conditionally assign field value using VBA?

분류에서Dev

Counting and grouping records up to a certain value

분류에서Dev

PHP displaying a certain amount of records per div

분류에서Dev

Check the records which are not in the subquery DB2

분류에서Dev

Find Duplicate Rows/Records from Table

분류에서Dev

using wildcard to find records of a textbox linked to a query

분류에서Dev

rails find records containing specific word

분류에서Dev

split 1 record into 4 records(transpose row into column) in oracle

분류에서Dev

how to select some record by random between the some records?

분류에서Dev

Copy only records that do not exist in the target table

분류에서Dev

getting records which are different from two fastq files

분류에서Dev

How do I get a records for a table that do not exist in another table?

분류에서Dev

How to find out insertion time of records in an oracle table

분류에서Dev

How to find duplicate between staging and main table with millions records

분류에서Dev

SQL: find records having data for each month in a given date range

분류에서Dev

Find highest threshold across 5 columns of dataframe to obtain n records

분류에서Dev

Which PCI slots belong to which CPUs

분류에서Dev

Previous / Next Links do not work on first and last records in model (rails)

분류에서Dev

How do you investigate a system crash when there are no records/logs?

분류에서Dev

writing a query to to generate two records from one record based on some condition

분류에서Dev

Fastest way to SELECT through MySQL table records backwards from a certain row?

분류에서Dev

Find followers of an element in a certain scope, which aren't siblings

분류에서Dev

Check if record doesn't belong to user

분류에서Dev

min (records) 및 max (records) 찾기

분류에서Dev

Mysql Unique records, where multiple records exist

분류에서Dev

Counting the number of records per month in an Access table which holds 25 years worth of data

분류에서Dev

Import Multiple Records Into CRM

Related 관련 기사

  1. 1

    Select records that are not associated with the other record

  2. 2

    SQL query to find unreferenced records

  3. 3

    How do I loop through certain records, check a query, and conditionally assign field value using VBA?

  4. 4

    Counting and grouping records up to a certain value

  5. 5

    PHP displaying a certain amount of records per div

  6. 6

    Check the records which are not in the subquery DB2

  7. 7

    Find Duplicate Rows/Records from Table

  8. 8

    using wildcard to find records of a textbox linked to a query

  9. 9

    rails find records containing specific word

  10. 10

    split 1 record into 4 records(transpose row into column) in oracle

  11. 11

    how to select some record by random between the some records?

  12. 12

    Copy only records that do not exist in the target table

  13. 13

    getting records which are different from two fastq files

  14. 14

    How do I get a records for a table that do not exist in another table?

  15. 15

    How to find out insertion time of records in an oracle table

  16. 16

    How to find duplicate between staging and main table with millions records

  17. 17

    SQL: find records having data for each month in a given date range

  18. 18

    Find highest threshold across 5 columns of dataframe to obtain n records

  19. 19

    Which PCI slots belong to which CPUs

  20. 20

    Previous / Next Links do not work on first and last records in model (rails)

  21. 21

    How do you investigate a system crash when there are no records/logs?

  22. 22

    writing a query to to generate two records from one record based on some condition

  23. 23

    Fastest way to SELECT through MySQL table records backwards from a certain row?

  24. 24

    Find followers of an element in a certain scope, which aren't siblings

  25. 25

    Check if record doesn't belong to user

  26. 26

    min (records) 및 max (records) 찾기

  27. 27

    Mysql Unique records, where multiple records exist

  28. 28

    Counting the number of records per month in an Access table which holds 25 years worth of data

  29. 29

    Import Multiple Records Into CRM

뜨겁다태그

보관