Skip to content
Advertisement

Multiple JOINs to the same subquery expression

I’ve recently been teaching myself SQL, and have been working on a toy project to do so. Here is a sample schema:

As part of this project, I have a query that gets a list of users, with information populated relative to the currently authenticated user.

A simplified version of the query looks like this:

Then, at some endpoints, I want to return objects which have one or more users as sub-objects. In order to do this, I’ve been JOINing tables to the above query as a subquery, but when the returned object has multiple users (e.g., an invite to an event has a sending user, a receiving user, and a user that owns the event in question), the resulting query can end up pretty repetitive:

My questions are:

  1. Is repeating a subquery like this a performance issue during execution, assuming that the INNER JOINs all match on just a single row?

  2. If not, is the additional parsing required for $select_invites_query a significant concern at all (especially as $select_users_query grows big and complex)?

  3. Would using a variable here be a good idea, or a bad idea? From my inspection of EXPLAIN it seems as though MySQL is able to handle these JOINs pretty efficiently, but would defining a variable force MySQL to pull the unfiltered result set into memory before JOINing?

See SQL Fiddle schema here.

Advertisement

Answer

Since you appear to need self joins of same query, consider a Common Table Expression (CTE) (available in MySQL 8.0+) and with PHP parameterization. Below demonstrates with PHP’s mysqli API in object-oriented and procedural styles:

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