0

I have a tables for jobs and bids. Each job has many bids. There is a bid column "is_selected" that is a boolean. Only one bid can be is_selected=true for a job.

My question is that I want to return the number of jobs where all bids are is_selected=false.

So for example,

Job 1 has bids a=true, b=false, c=false, d=false 
Job 2 has bids a=false, b=false, c=false
Job 3 has bids a=false, b=false
Job 4 has no bids

The result of this query should return a query with 3 jobs (only Job 1 has selected a bidder; so it should return job 2, 3, 4).

How can this be done in postgresql or ActiveRecord/Rails?


Update with data structure:

3 tables

Event (has_many jobs)

Job (has_many bids, belongs_to event)

  • event_id (integer)

Bid (belongs_to job)

  • job_id (integer)

  • is_selected (Boolean)

2
  • If you want a good answer you need to provide better examples of your data as it's stored in the db. I can't tell what your schema looks like from this. And it's a good bet it's suboptimal as well. Commented Dec 29, 2013 at 0:41
  • I updated the table information Commented Dec 29, 2013 at 5:00

2 Answers 2

1

here is one way to do it in ruby - not as efficient as doing it at the database

all_jobs = Job.includes(:bids)
logger.debug "ALL JOBS: #{all_jobs.length}"

jobs = all_jobs.reject { |job| job.bids.detect(&:is_selected) }
logger.debug "UNSELECTED JOBS #{jobs.length}"
Sign up to request clarification or add additional context in comments.

2 Comments

how would you do the sql query at the database level?
How are you storing these data in the database?
1

This should work as a pure SQL solution:

select count(1) 
from jobs 
where id not in (select distinct job_id from bids where is_selected=true)

assuming you only want to know the total number of jobs that have no bids. If you want the details of the jobs you can replace the contents of the select clause.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.