Skip to content
Advertisement

Join many to many tables optionally

I have below tables

User

Intrest

Hobby

User_Intrest

User_Hobby

Now to find user ids who have both interests Eating and Sleeping I have written

Output

Same as above I also can find user ids with hobbies Smoking, Hiking, Browsing as below

Output

Now I want to mix these two optionally in a way that if only interests are passed then users with those interests will be found or if only hobbies are passed then users with those hobbies are found or if both interests and hobbies are passed then users with those interests as well as hobbies are found

Update: This is part of a spring data rest api with native query where query parameters are optional. Below is a working example for finding users for intrests. Now I want to expand it to include hobbies so both will be used if both are passed in the request to find users

Advertisement

Answer

OK, the problem becomes a lot clearer when you use explicit joins (instead of the implicit, depreciated, comma-separated joins). You then see that you need to use left joins to allow a record to be returned when there is match.

  • Its best practice not to use reserved words such as user or user_id as you will always need to escape them.

  • Aside from the id column, there is no need to prepend the table name to a column name e.g. hobby_name should just be name – you’re just giving yourself more typing as it stands.

  • Interest is not spelt Intrest 🙂

  • If you provide DDL/DML for the sample data then its a lot easier for us to test.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement