[Solved] mySQL list profiles and movies using complex joins in one query but three tables

EverSQL Database Performance Knowledge Base

mySQL list profiles and movies using complex joins in one query but three tables

Database type:

Overview: I want to get a list of profiles and the movies they like. All the output to be shown on one page. I am using mySQL and PHP, at moment running on localhost. Ideally i want this to be in one query, for speed.

Database table overview in mySQL as follow:

profile_tbl:
> id
> username
> about me
> gender
> hobbies
> profile_pic
> last_login


movies_tbl:
> id
> movie_name
> genre
> length
> rating
> description


profile_movies_rel_tbl
> id
> movie_id
> profile_id

Output:

I want to show 10 profiles and list of the all the movies they like. I was thinking following query:

SELECT  profile_tbl.*, movies_tbl.* FROM profile_tbl
LEFT JOIN profile_movies_rel_tbl
ON profile_movies_rel_tbl.movie_id = movies_tbl.id
LEFT JOIN profile_tbl
ON profile_tbl.id= profile_movies_rel_tbl.profile_id LIMIT 10

I also have a second issue, where I want to lists all the profile that have selected movie has favorite, again the page should list profiles and movies together. In this case, i was thinking of using the above query and adding following:

WHERE profile_movies_rel_tbl.movie_id = 4

Any one need more info, please leave comment.

thanks

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `profile_movies_rel_tbl` ADD INDEX `profile_rel_idx_profile_id` (`profile_id`);
The optimized query:
SELECT
        profile_tbl.*,
        movies_tbl.* 
    FROM
        profile_tbl 
    LEFT JOIN
        profile_movies_rel_tbl 
            ON profile_movies_rel_tbl.movie_id = movies_tbl.id 
    LEFT JOIN
        profile_tbl 
            ON profile_tbl.id = profile_movies_rel_tbl.profile_id LIMIT 10

Related Articles



* original question posted on StackOverflow here.