Supposed that we have classes Person, Character, and PersonCharacter and their corresponding structure in following data structure and data in MySQL database.
table persons
[
{ id: 1, name: peter },
{ id: 2, name: mary },
{ id: 3, name: joe },
{ id: 4, name: paul },
{ id: 5, name: may },
]
table characters
[
{ id: 101, description: cheerful },
{ id: 102, description: nervous },
{ id: 103, description: greedy },
{ id: 104, description: sincere },
{ id: 105, description: naive },
{ id: 106, description: firm },
]
table person_characters
[
{id: 1000, person_id: 1, character_id: 101},
{id: 1001, person_id: 1, character_id: 103},
{id: 1002, person_id: 1, character_id: 106},
{id: 1003, person_id: 2, character_id: 102},
{id: 1004, person_id: 2, character_id: 104},
{id: 1005, person_id: 3, character_id: 102},
{id: 1006, person_id: 3, character_id: 105},
{id: 1007, person_id: 4, character_id: 104},
{id: 1008, person_id: 5, character_id: 101},
{id: 1009, person_id: 5, character_id: 106},
]
How can I write a SQL statement, if possible with help of Rails, that can find out that with persons who have particular characters? For example, persons with character both firm and cheerful are may and peter.
The question seems typical but it is hard to find the answer by search engines.
NOTE use only one of those statements after the AND inside the join. I’m just showing either approach (if you do or do not have the ID(s) of the characters(s) to look for.