[Solved] MySQL inner join only select 1 row
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

MySQL inner join only select 1 row

Database type:

I have a table (sampleTable) of website access dates as year-month-day, timestamps as year-month-day hour-minutes-seconds, user ids and website access ids. I want to select the access ids which correspond to the first access that occurred on the most recent day. So far I have attempted this with

select userID, MAX(dayAccessed) as latestDay from sampleTable group by userID;

which returns the most recent day. I then have used this in a inner join to rejoin this query with the original table which orders the columns correctly. My problem is that I cannot access the earliest access id on the most recent day for both user ids as

SELECT sampleTable.dayTimeAccessed, sampleTable.userID, latest.latestDay 
    (SELECT userID, MAX(dayTimeAccessed) AS latestDay 
    from sampleTable 
    group by userID) AS latest 
INNER JOIN sampleTable 
ON sampleTable.userID = latest.userID AND 
limit 1;

only returns one field with the first userID matched.

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. 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.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `sampleTable` ADD INDEX `sampletable_idx_userid_dayaccessed` (`userID`,`dayAccessed`);
The optimized query:
        MAX(sampleTable.dayAccessed) AS latestDay 

Related Articles

* original question posted on StackOverflow here.