0

I have the following postgresql query which selects a few fields from a table called statement_bank:

SELECT statement_id, statement_value FROM statement_bank WHERE category_id=6 AND level=7 

I have another table called statement_records, and the fields for that table are:

date | user_id | statement_id

Once a statement is used for a particular user_id, the statement_id is recorded in the statement_records table. This may be recorded a few times for different users.

I am looking to run the first query so that it only returns the statement_id's from the statement_bank table if it exists in the statement_records table between a specific date e.g. between 01-01-2013 AND 01-01-2014

Any suggestions on how I can achieve this?

Thanks

1
  • What about using a JOIN ? Commented Oct 10, 2014 at 8:19

1 Answer 1

2

I think you just want an exists clause. Based on the information you provided, it would look something like:

SELECT statement_id, statement_value
FROM statement_bank sr
WHERE category_id=6 AND level=7 and
      exists (select 1
              from statement_record sr
              where sr.user_id = sb.user_id and
                    sr.statement_id = sb.statement_id and
                    sr.date between '2013-01-01' and '2013-12-31'
             );

Note: I am assuming you don't really want matches on 2014-01-01, but only through the end of 2013.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that Gordon. Where sr.user_id=sb.user_id, i do not have user_id in the statement_bank table, the table just holds unique statements which can then be applied to number of users, hence the reason the statement_id may exist multiple times in the statement_record table. Should i just remove the line that reads sr.user_id = sb.user_id? will duplicate existence of the statement_id in the statement_records table cause a problem then?

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.