I have a MariaDB 10.5.10 database, with a table activity
made of 150,000 rows. it holds:
- an
id
field (integer, primary key) - a
tenant
. There are about 85,000 rows with tenant = 12 - an
activity_type
(integer, acting as a key to another tableactivity_type
)
Another table, activity_type
, has 6 rows, with an id
(primary key, integer)
This query, which is generated from an ORB (and which I can virtually not modify) requires about 4-5 seconds to execute, and I would like to make it run faster:
select count(activity.id) from activity
left join activity_type on activity.type = activity_type.id
where tenant = 12 ;
When I remove the left join
row, it runs much faster, about 0.7 seconds.
Using explain
, I can see that without left join
, the extra
column mentions using index
(actually, the index on the tenant
column):
explain select SQL_NO_CACHE count(activity.id) from activity
where tenant = 12;
But with left join
the extra
column is empty:
explain select SQL_NO_CACHE count(activity.id) from activity
left join activity_type on activity.type = activity_type.id
where tenant = 12;
And with left join
but NO where
clause, it also shows Using index
:
explain select SQL_NO_CACHE count(activity.id) from activity
left join activity_type on activity.type = activity_type.id;
Could you please help me improving the performance when both the LEFT JOIN
and the WHERE
statements are present?
Please note that:
- the
LEFT JOIN
does not add any rows to the results, because there is only oneactivity_type
row per activity (I have also tried to add aUNIQUE
index on theactivity_type.id
, but it does not change anything on performance) - however I need the
LEFT JOIN
statement, because in some cases, the users might want to add more criteria (in thewhere
clause) related to the fields in theactivity_type
table.
Many thanks!
activity_type
oractivity.type
-- You have inconsistencies.