GeekedOut
GeekedOut

Reputation: 17185

How to query for items related to a category?

I am a bit braindead from programming non-stop today, and it seems easy but my brain is just not there at this point.

I have a table of records. Each record belongs to one or more categories. The categories and records are joined by an intermediate table which has record_id and category_id columns.

What I want to do is query for records that belong to the same categories as the current record. How would I go about that?

Thanks!!

Upvotes: 0

Views: 69

Answers (1)

driangle
driangle

Reputation: 11779

Assuming your association table is called 'record_category'. And that you already have the category ids for the 'current record' in a list.

select r.* from records r join record_category rc on rc.record_id=r.record_id where rc.category_id in( ?category_ids)

If all you have is the current record's id. Then this would be a more complete query:

select r.* from record r join record_category rc on rc.record_id=r.record_id where rc.category_id in(select rc.category_id from record_category rc where record_id=?) group by r.record_id

Replace ? with the actual value of the id, or use it in a prepared statement (depends on the language).

Upvotes: 1

Related Questions