MySQL left join VERY slow, and usuall hangs forever - mysql

I have 2 tables, ticket_data and nps_data.
ticket_data hold general IT issue information and nps_data holds user feedback.
A basic idea of the tables are:
ticket_data table.
aprox. 1,500,000 rows: 30 fields:
Index on ticket_number, logged_date, logged_team, resolution_date
|ticket_number | logged_date | logged_team | resolution_date |
| I00001 | 2017-01-01 | Help Desk | 2017-01-02 |
| I00002 | 2017-02-01 | Help Desk | 2017-03-01 |
| I00010 | 2017-03-04 | desktop sup | 2017-03-04 |
Obviously there are lots of other fields but this is what Im working with
nps_data table
aprox 83,000 rows: 10 fields:
index ticket_number
|ticket_number | resolving team| q1_score|
| I00001 | helpdesk | 5 |
| I00002 | desktop sup | 0 |
| I00010 | desktop sup | 10 |
when I do a simple query such as
select a.*, b.q1_score from
(select * from ticket_data
where resolution_date > '2017-01-01') a
left join nps_data b
on a.ticket_number = b.ticket_number
The query takes forever to run, and when I say that, I mean I stop the query after 10 mins.
However if I run the query to join ticket_data with a table called ticket_details, which has over 1,000,000 rows using the following query
select *
(select * from ticket_data
where resolution_date > '2017-01-01') a
left join ticket_details b
on a.ticket_number = b.ticket_number
the query takes about 1.3 seconds to run.

In the query above, you have a subquery with the alias a that is not running on an index. You are querying the field resolution_date, which is un-indexed.
The simple fix would be to add an index to that field.
Ticket number is indexed. This is probably why when you join on that, the query runs faster.
The other way to further optimize this would not to do select * in your subquery (which is bad practice in a production system anyway). It creates more overhead for the DBMS to pass all results up in the subquery.
Another way would be to do a partial index on the column such as:
create index idx_tickets on ticket_data(ticket_number) where resolution_date > '2017-01-01'
But I would only do that if the timestamp of '2017-01-01' is a constant that will always be used.
You could also create a composite index, so the query engine will run an Index Only Scan whereby it pulls the data straight from the index without having to go back to the table.
In order for me to reference something on this, I would need to know what DBMS you are running on.
Of course, all of this depends on what type of DBMS you are running.

Related

Self join on a huge table with conditions is taking a lot of time , optimize query

I have a master table which has details.
I wanted to find all the combinations for a product in that session with every other product in that particular sessions for all sessions.
create table combinations as
select
a.main_id,
a.sub_id as sub_id_x,
b.sub_id as sub_id_y,
count(*) as count1,
a.dates as rundate
from
master_table a
left join
master_table b
on a.session_id = b.session_id
and a.visit_number = b.visit_number
and a.main_id = b.main_id
and a.sub_id != b.sub_id
where
a.sub_id is not null
and b.sub_id is not null
group by
a.main_id,
a.sub_id,
b.sub_id,
rundate;
I did a explain on query
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+----------------------------------------------------+
| 1 | SIMPLE | a | NULL | ALL | NULL | NULL | NULL | NULL | 298148 | 90.00 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | b | NULL | ALL | NULL | NULL | NULL | NULL | 298148 | 0.08 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+----------------------------------------------------+
The main issue is, my master table consists of 80 million rows. This query is taking more than 24 hours to execute.
All the columns are indexed and I am doing a self join.
Would creating a like table first 'master_table_2' and then doing a join would make my query faster?
Is there any way to optimize the query time?
As your table consists of a lot of rows, the join query will take a lot of time if it is not optimized properly and the WHERE clause is not used properly. But an optimized query could save your time and effort. The following link has a good explanation about the optimization of the join queries and its facts -
Optimization of Join Queries
#Marcus Adams has already provided a similar answer here
Another option is you can select individually and process in the code end for the optimization. But it is only applicable in some specific conditions only. You will have to try to compare both processes (join query and code end execution) and check the performance. I have got better performance once using this method.
Suppose a join query is like as the following -
SELECT A.a1, B.b1, A.a2
FROM A
INNER JOIN B
ON A.a3=B.b3
WHERE B.b3=C;
What I am trying to say is query individually from A and B satisfying the necessary conditions and then try to get your desired result from the code end.
N.B. : It is an unorthodox way and it could not be taken as granted to be applicable in all criteria.
Hope it helps.

MySQL InnoDB indexes slowing down sorts

I am using MySQL 5.6 on FreeBSD and have just recently switched from using MyISAM tables to InnoDB to gain advances of foreign key constraints and transactions.
After the switch, I discovered that a query on a table with 100,000 rows that was previously taking .003 seconds, was now taking 3.6 seconds. The query looked like this:
SELECT *
-> FROM USERS u
-> JOIN MIGHT_FLOCK mf ON (u.USER_ID = mf.USER_ID)
-> WHERE u.STATUS = 'ACTIVE' AND u.ACCESS_ID >= 8 ORDER BY mf.STREAK DESC LIMIT 0,100
I noticed that if I removed the ORDER BY clause, the execution time dropped back down to .003 seconds, so the problem is obviously in the sorting.
I then discovered that if I added back the ORDER BY but removed indexes on the columns referred to in the query (STATUS and ACCESS_ID), the query execution time would take the normal .003 seconds.
Then I discovered that if I added back the indexes on the STATUS and ACCESS_ID columns, but used IGNORE INDEX (STATUS,ACCESS_ID), the query would still execute in the normal .003 seconds.
Is there something about InnoDB and sorting results when referencing an indexed column in a WHERE clause that I don't understand?
Or am I doing something wrong?
EXPLAIN for the slow query returns the following results:
+----+-------------+-------+--------+--------------------------+---------+---------+---------------------+-------+---------------------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+--------------------------+---------+---------+---------------------+-------+---------------------------------------------------------------------+
| 1 | SIMPLE | u | ref | PRIMARY,STATUS,ACCESS_ID | STATUS | 2 | const | 53902 | Using index condition; Using where; Using temporary; Using filesort |
| 1 | SIMPLE | mf | eq_ref | PRIMARY | PRIMARY | 4 | PRO_MIGHT.u.USER_ID | 1 | NULL |
+----+-------------+-------+--------+--------------------------+---------+---------+---------------------+-------+---------------------------------------------------------------------+
EXPLAIN for the fast query returns the following results:
+----+-------------+-------+--------+---------------+---------+---------+----------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+----------------------+------+-------------+
| 1 | SIMPLE | mf | index | PRIMARY | STREAK | 2 | NULL | 100 | NULL |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | PRO_MIGHT.mf.USER_ID | 1 | Using where |
+----+-------------+-------+--------+---------------+---------+---------+----------------------+------+-------------+
Any help would be greatly appreciated.
In the slow case, MySQL is making an assumption that the index on STATUS will greatly limit the number of users it has to sort through. MySQL is wrong. Presumably most of your users are ACTIVE. MySQL is picking up 50k user rows, checking their ACCESS_ID, joining to MIGHT_FLOCK, sorting the results and taking the first 100 (out of 50k).
In the fast case, you have told MySQL it can't use either index on USERS. MySQL is using its next-best index, it is taking the first 100 rows from MIGHT_FLOCK using the STREAK index (which is already sorted), then joining to USERS and picking up the user rows, then checking that your users are ACTIVE and have an ACCESS_ID at or above 8. This is much faster because only 100 rows are read from disk (x2 for the two tables).
I would recommend:
drop the index on STATUS unless you frequently need to retrieve INACTIVE users (not ACTIVE users). This index is not helping you.
Read this question to understand why your sorts are so slow. You can probably tune InnoDB for better sort performance to prevent these kind of problems.
If you have very few users with ACCESS_ID at or above 8 you should see a dramatic improvement already. If not you might have to use STRAIGHT_JOIN in your select clause.
Example below:
SELECT *
FROM MIGHT_FLOCK mf
STRAIGHT_JOIN USERS u ON (u.USER_ID = mf.USER_ID)
WHERE u.STATUS = 'ACTIVE' AND u.ACCESS_ID >= 8 ORDER BY mf.STREAK DESC LIMIT 0,100
STRAIGHT_JOIN forces MySQL to access the MIGHT_FLOCK table before the USERS table based on the order in which you specify those two tables in the query.
To answer the question "Why did the behaviour change" you should start by understanding the statistics that MySQL keeps on each index: http://dev.mysql.com/doc/refman/5.6/en/myisam-index-statistics.html. If statistics are not up to date or if InnoDB is not providing sufficient information to MySQL, the query optimiser can (and does) make stupid decisions about how to join tables.

MySQL has indexed tables and EXPLAIN looks good, but still not using index

I am trying to optimize a query, and all looks well when I got to "EXPLAIN" it, but it's still coming up in the "log_queries_not_using_index".
Here is the query:
SELECT t1.id_id,t1.change_id,t1.like_id,t1.dislike_id,t1.user_id,t1.from_id,t1.date_id,t1.type_id,t1.photo_id,t1.mobile_id,t1.mobiletype_id,t1.linked_id
FROM recent AS t1
LEFT JOIN users AS t2 ON t1.user_id = t2.id_id
WHERE t2.active_id=1 AND t1.postedacommenton_id='0' AND t1.type_id!='Friends'
ORDER BY t1.id_id DESC LIMIT 35;
So it grabs like a 'wallpost' data, and then I joined in the USERS table to make sure the user is still an active user (the number 1), and two small other "ANDs".
When I run this with the EXPLAIN in phpmyadmin it shows
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | t1 | index | user_id | PRIMARY | 4 | NULL | 35 | Using where
1 | SIMPLE | t2 | eq_ref | PRIMARY,active_id | PRIMARY | 4 | hnet_user_info.t1.user_id | 1 | Using where
It shows the t1 query found 35 rows using "WHERE", and the t2 query found 1 row (the user), using "WHERE"
So I can't figure out why it's showing up in the log_queries_not_using_index report.
Any tips? I can post more info if you need it.
tldr; ignore the "not using index warning". A query execution time of 1.3 milliseconds is not a problem; there is nothing to optimize here - look at the entire performance profile to find bottlenecks.
Trust the database engine. The database query planner will use indices when it determines that doing so is beneficial. In this case, due to the low cardinality estimates (35x1), the query planner decided that there was no reason to use indices for the actual execution plan. If indices were used in a trivial case like this it could actually increase the query execution time.
As always, use the 97/3 rule.

Unable to optimize MySQL query which uses a ORDER BY clause

I'm using Drupal 6 with MySQL version 5.0.95 and at an impasse where one of my queries which displays content based on most recent article date slows down and because of the frequency of being used kills the site performance altogether. The query in question is as below:
SELECT n.nid,
n.title,
ma.field_article_date_format_value,
ma.field_article_summary_value
FROM node n
INNER JOIN content_type_article ma ON n.nid=ma.nid
INNER JOIN term_node tn ON n.nid=tn.nid
WHERE tn.tid= 153
AND n.status=1
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0, 11;
The EXPLAIN of the query shows the below result:
+----+-------------+-------+--------+--------------------------+---------+---------+----------------------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+--------------------------+---------+---------+----------------------+-------+---------------------------------+
| 1 | SIMPLE | tn | ref | PRIMARY,nid | PRIMARY | 4 | const | 19006 | Using temporary; Using filesort |
| 1 | SIMPLE | ma | ref | nid,ix_article_date | nid | 4 | drupal_mm_stg.tn.nid | 1 | |
| 1 | SIMPLE | n | eq_ref | PRIMARY,node_status_type | PRIMARY | 4 | drupal_mm_stg.ma.nid | 1 | Using where |
+----+-------------+-------+--------+--------------------------+---------+---------+----------------------+-------+---------------------------------+
This query seemed relatively simple and straight forward and retrieves articles which belong to a category (term) 153 and are of status 1 (published). But apparently Using temporary table and Using filesort means the query is bound to fail from what I've learnt browsing about it.
Removing field_article_date_format_value from the ORDER BY clause solves the Using temporary; Using filesort reduces the query execution time but is required and cannot be traded off, unfortunately same holds equally true for the site performance.
My hunch is that most of the trouble comes from the term_node table which maps articles to categories and is a many-many relationship table meaning if article X is associated to 5 categories C1....C5 it will have 5 entries in that table, this table is from out-of-the-box drupal.
Dealing with heavy DB content is something new to me and going through some of the similar queries (
When ordering by date desc, "Using temporary" slows down query,
MySQL performance optimization: order by datetime field) I tried to create a composite index for the content_type_article whose datetime field is used in the ORDER BY clause along with another key (nid) in it and tried to FORCE INDEX.
SELECT n.nid, n.title,
ma.field_article_date_format_value,
ma.field_article_summary_value
FROM node n
INNER JOIN content_type_article ma FORCE INDEX (ix_article_date) ON n.nid=ma.nid
INNER JOIN term_node tn ON n.nid=tn.nid
WHERE tn.tid= 153
AND n.status=1
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0, 11;
The result and the following EXPLAIN query did not seem to help much
+----+-------------+-------+--------+--------------------------+-----------------+---------+----------------------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+--------------------------+-----------------+---------+----------------------+-------+---------------------------------+
| 1 | SIMPLE | tn | ref | PRIMARY,nid | PRIMARY | 4 | const | 18748 | Using temporary; Using filesort |
| 1 | SIMPLE | ma | ref | ix_article_date | ix_article_date | 4 | drupal_mm_stg.tn.nid | 1 | |
| 1 | SIMPLE | n | eq_ref | PRIMARY,node_status_type | PRIMARY | 4 | drupal_mm_stg.ma.nid | 1 | Using where |
+----+-------------+-------+--------+--------------------------+-----------------+---------+----------------------+-------+---------------------------------+
The fields n.nid, ca.nid, ma.field_article_date_format_value are all indexed. Querying the DB with Limit 0,11 takes approximately 7-10 seconds with the ORDER BY clause but without it the query barely takes a second. The database engine is MyISAM. Any help on this would be greatly appreciated.
Any answer that could help me in getting this query like a normal one (at the same speed as a query without sort by date) would be great. My attempts with creating a composite query as a combination of nid and field_article_date_format_value and use in the query did not help the cause. I'm open to providing additional info on the problem and any new suggestions.
Taking a look at your query and the explain, it seems like having the n.status=1 in the where clause is making the search very inefficient because you need to return the whole set defined by the joins and then apply the status = 1. Try starting the join from the term_node table that is inmediately filtered by the WHERE and then make the joins adding the status condition immediately. Give it a try and please tell me how it goes.
SELECT n.nid, n.title,
ma.field_article_date_format_value,
ma.field_article_summary_value
FROM term_node tn
INNER JOIN node n ON n.nid=tn.nid AND n.status=1
INNER JOIN content_type_article ma FORCE INDEX (ix_article_date) ON n.nid=ma.nid
WHERE tn.tid= 153
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0, 11;
Using temporary; Using filesort means only that MySQL needs to construct a temporary result table and sort it to get the result you need. This is often a consequence of the ORDER BY ... DESC LIMIT 0,n construct you're using to get the latest postings. In itself it's not a sign of failure. See this: http://www.mysqlperformanceblog.com/2009/03/05/what-does-using-filesort-mean-in-mysql/
Here are some things to try. I am not totally sure they'll work; it's hard to know without having your data to experiment with.
Is there a BTREE index on content_type_article.field_article_date_format_value ? If so, that may help.
Do you HAVE to display the 11 most recent articles? Or can you display the 11 most recent articles that have appeared in the last week or month? If so you could add this line to your WHERE clause. It would filter your stuff by date rather than having to look all the way back to the beginning of time for matching articles. This will be especially helpful if you have a long-established Drupal site.
AND ma.field_article_date_format_value >= (CURRENT_TIME() - INTERVAL 1 MONTH)
First, try to flip the order of the INNER JOIN operations. Second, incorporate the tid=153 into the join criterion. This MAY reduce the size of the temp table you need to sort. All together my suggestions are as follows:
SELECT n.nid,
n.title,
ma.field_article_date_format_value,
ma.field_article_summary_value
FROM node n
INNER JOIN term_node tn ON (n.nid=tn.nid AND tn.tid = 153)
INNER JOIN content_type_article ma ON n.nid=ma.nid
WHERE n.status=1
AND ma.field_article_date_format_value >= (CURRENT_TIME() - INTERVAL 1 MONTH)
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0, 11;
Those are
1) Covering indexes
I think the simple answer may be "covering indexes".
Especially on the content_type_article table. The "covering index" has the expression in the ORDER BY as the leading column, and includes all of the columns that are being referenced by the query. Here's the index I created (on my test table):
CREATE INDEX ct_article_ix9
ON content_type_article
(field_article_date_format_value, nid, field_article_summary_value);
And here's an excerpt of the EXPLAIN I get from the query (after I build example tables, using the InnoDB engine, including a covering index on each table):
_type table type key ref Extra
------ ----- ----- -------------- ----------- ------------------------
SIMPLE ma index ct_article_ix9 NULL Using index
SIMPLE n ref node_ix9 ma.nid Using where; Using index
SIMPLE tn ref term_node_ix9 n.nid,const Using where; Using index
Note that there's no 'Using filesort' shown in the plan, and the plan shows 'Using index' for each table referenced in the query, which basically means that all of the data needed by the query is retrieved from the index pages, with no need to reference any pages from the underlying table. (Your tables have a lot more rows than my test tables, but if you can get an explain plan that looks like this, you may get better performance.)
For completeness, here's the entire EXPLAIN output:
+----+-------------+-------+-------+---------------+----------------+---------+---------------------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+----------------+---------+-------- ------------+------+--------------------------+
| 1 | SIMPLE | ma | index | NULL | ct_article_ix9 | 27 | NULL | 1 | Using index |
| 1 | SIMPLE | n | ref | node_ix9 | node_ix9 | 10 | testps.ma.nid,const | 11 | Using where; Using index |
| 1 | SIMPLE | tn | ref | term_node_ix9 | term_node_ix9 | 10 | testps.n.nid,const | 11 | Using where; Using index |
+----+-------------+-------+-------+---------------+----------------+---------+---------------------+------+--------------------------+
3 rows in set (0.00 sec)
I made no changes to your query, except to omit the FORCE INDEX hint. Here are the other two "covering indexes" that I created on the other two tables referenced in the query:
CREATE INDEX node_ix9
ON node (`nid`,`status`,`title`);
CREATE INDEX term_node_ix9
ON term_node (nid,tid);
(Note that if nid is the clustering key on the node table, you may not need the covering index on the node table.)
2) Use correlated subqueries in place of joins?
If the previous idea doesn't improve anything, then, as another alternative, since the original query is returning a maximum of 11 rows, you might try rewriting the query to avoid the join operations, and instead make use of correlated subqueries. Something like the query below.
Note that this query differs significantly from the original query. The difference is that with this query, a row from the context_type_article table will be returned only one time. With the query using the joins, a row from that table could be matched to multiple rows from node and term_node tables, which would return that same row more than once. This may be viewed as either desirable or undesirable, it really depends on the cardinality, and whether the resultset meets the specification.
SELECT ( SELECT n2.nid
FROM node n2
WHERE n2.nid = ma.nid
AND n2.status = 1
LIMIT 1
) AS `nid`
, ( SELECT n3.title
FROM node n3
WHERE n3.nid = ma.nid
AND n3.status = 1
LIMIT 1
) AS `title`
, ma.field_article_date_format_value
, ma.field_article_summary_value
FROM content_type_article ma
WHERE EXISTS
( SELECT 1
FROM node n1
WHERE n1.nid = ma.nid
AND n1.status = 1
)
AND EXISTS
( SELECT 1
FROM term_node tn
WHERE tn.nid = ma.nid
AND tn.tid = 153
)
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0,11
(Sometimes, a query using this type of "orrelated subquery" can have considerably WORSE performance than an equivalent query that does join operations. But in some cases, a query like this can actually perform better, especially given a very limited number of rows being returned.)
Here's the explain output for that query:
+----+--------------------+-------+-------+---------------+----------------+---------+---------------------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+-------+---------------+----------------+---------+---------------------+------+--------------------------+
| 1 | PRIMARY | ma | index | NULL | ct_article_ix9 | 27 | NULL | 11 | Using where; Using index |
| 5 | DEPENDENT SUBQUERY | tn | ref | term_node_ix9 | term_node_ix9 | 10 | testps.ma.nid,const | 13 | Using where; Using index |
| 4 | DEPENDENT SUBQUERY | n1 | ref | node_ix9 | node_ix9 | 10 | testps.ma.nid,const | 12 | Using where; Using index |
| 3 | DEPENDENT SUBQUERY | n3 | ref | node_ix9 | node_ix9 | 10 | testps.ma.nid,const | 12 | Using where; Using index |
| 2 | DEPENDENT SUBQUERY | n2 | ref | node_ix9 | node_ix9 | 10 | testps.ma.nid,const | 12 | Using where; Using index |
+----+--------------------+-------+-------+---------------+----------------+---------+---------------------+------+--------------------------+
5 rows in set (0.00 sec)
Note that again, each access is 'Using index', which means the query is satisfied directly from index pages, rather than having to visit any data pages in the underlying table.
Example tables
Here are the example tables (along with the indexes) that I built and populated, based on the information from your question:
CREATE TABLE `node` (`id` INT PRIMARY KEY, `nid` INT, `title` VARCHAR(10),`status` INT);
CREATE INDEX node_ix9 ON node (`nid`,`status`,`title`);
INSERT INTO `node` VALUES (1,1,'foo',1),(2,2,'bar',0),(3,3,'fee',1),(4,4,'fi',0),(5,5,'fo',1),(6,6,'fum',0),(7,7,'derp',1);
INSERT INTO `node` SELECT id+7,nid+7,title,`status` FROM node;
INSERT INTO `node` SELECT id+14,nid+14,title,`status` FROM node;
INSERT INTO `node` SELECT id+28,nid+28,title,`status` FROM node;
INSERT INTO `node` SELECT id+56,nid+56,title,`status` FROM node;
CREATE TABLE content_type_article (id INT PRIMARY KEY, nid INT, field_article_date_format_value DATETIME, field_article_summary_value VARCHAR(10));
CREATE INDEX ct_article_ix9 ON content_type_article (field_article_date_format_value, nid, field_article_summary_value);
INSERT INTO content_type_article VALUES (1001,1,'2012-01-01','foo'),(1002,2,'2012-01-02','bar'),(1003,3,'2012-01-03','fee'),(1004,4,'2012-01-04','fi'),(1005,5,'2012-01-05','fo'),(1006,6,'2012-01-06','fum'),(1007,7,'2012-01-07','derp');
INSERT INTO content_type_article SELECT id+7,nid+7, DATE_ADD(field_article_date_format_value,INTERVAL 7 DAY),field_article_summary_value FROM content_type_article;
INSERT INTO content_type_article SELECT id+14,nid+14, DATE_ADD(field_article_date_format_value,INTERVAL 14 DAY),field_article_summary_value FROM content_type_article;
INSERT INTO content_type_article SELECT id+28,nid+28, DATE_ADD(field_article_date_format_value,INTERVAL 28 DAY),field_article_summary_value FROM content_type_article;
INSERT INTO content_type_article SELECT id+56,nid+56, DATE_ADD(field_article_date_format_value,INTERVAL 56 DAY),field_article_summary_value FROM content_type_article;
CREATE TABLE term_node (id INT, tid INT, nid INT);
CREATE INDEX term_node_ix9 ON term_node (nid,tid);
INSERT INTO term_node VALUES (2001,153,1),(2002,153,2),(2003,153,3),(2004,153,4),(2005,153,5),(2006,153,6),(2007,153,7);
INSERT INTO term_node SELECT id+7, tid, nid+7 FROM term_node;
INSERT INTO term_node SELECT id+14, tid, nid+14 FROM term_node;
INSERT INTO term_node SELECT id+28, tid, nid+28 FROM term_node;
INSERT INTO term_node SELECT id+56, tid, nid+56 FROM term_node;
MySQL is "optimizing" your query so that it selects from the term_node table first, even though you are specifying to select from node first. Not knowing the data, I'm not sure which is the optimal way. The term_node table is certainly where your performance issues are since ~19,000 records is being selected from there.
Limits without ORDER BY are almost always faster because MySQL stops as soon as it finds the specified limit. With an ORDER BY, it first has to find all the records and sort them, then get the specified limit.
The simple thing to try is moving your WHERE condition into the JOIN clause, which is where it should be. That filter is specific to the table being joined. This will make sure MySQL doesn't optimize it incorrectly.
INNER JOIN term_node tn ON n.nid=tn.nid AND tn.tid=153
A more complicated thing is to do a SELECT on the term_node table and JOIN on that. That's called a DERIVED TABLE and you will see it defined as such in the EXPLAIN. Since you said it was a many-to-many, I added a DISTINCT parameter to reduce the numbers of records to join on.
SELECT ...
FROM node n
INNER JOIN content_type_article ma FORCE INDEX (ix_article_date) ON n.nid=ma.nid
INNER JOIN (SELECT DISTINCT nid FROM term_node WHERE tid=153) tn ON n.nid=tn.nid
WHERE n.status=1
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0,11
MySQL 5.0 has some limitations with derived tables, so this may not work. Although there are work arounds.
You really want to avoid the sort operation happening at all if you can by taking advantage of a pre-sorted index.
To find out if this is possible, imagine your data denormalised into a single table, and ensure that everything that must be included in your WHERE clause is specifiable with a SINGLE VALUE. e.g. if you must use an IN clause on one of the columns, then sorting is inevitable.
Here's a screenshot of some sample data:
So, if you DID have your data denormalised, you could query on tid and status using single values and then sort by date descending. That would mean the following index in that case would work perfectly:
create index ix1 on denormalisedtable(tid, status, date desc);
If you had this, your query would only hit the top 10 rows and would never need to sort.
So - how do you get the same performance WITHOUT denormalising...
I think you should be able to use the STRAIGHT_JOIN clause to force the order that MySQL selects from the tables - you want to get it to select from the table you are SORTING last.
Try this:
SELECT n.nid,
n.title,
ma.field_article_date_format_value,
ma.field_article_summary_value
FROM node n
STRAIGHT_JOIN term_node tn ON n.nid=tn.nid
STRAIGHT_JOIN content_type_article ma ON n.nid=ma.nid
WHERE tn.tid= 153
AND n.status=1
ORDER BY ma.field_article_date_format_value DESC
LIMIT 0, 11;
The idea is to get MySQL to select from the node table and then from the term_node table and THEN FINALLY from the content_type_article table (the table containing the column you are sorting on).
This last join is your most important one and you want it to happen using an index so that the LIMIT clause can work without needing to sort the data.
This single index MIGHT do the trick:
create index ix1 on content_type_article(nid, field_article_date_format_value desc);
or
create index ix1 on content_type_article(nid, field_article_date_format_value desc, field_article_summary_value);
(for a covering index)
I say MIGHT, because I don't know enough about the MySQL optimiser to know if it's clever enough to handle the multiple 'nid' column values that will be getting fed into the content_type_article without having to resort the data.
Logically, it should be able to work quickly - e.g. if 5 nid values are getting fed into the final content_type_article table, then it should be able to get the top 10 of each directly from the index and merge the results together then pick the final top 10, meaning a total of 50 rows read from this table insted of the full 19006 that you're seeing currently.
Let me know how it goes.
If it works for you, further optimisation will be possible using covering indexes on the other tables to speed up the first two joins.

how can I optimize a query with multiple joins (already have indexes)?

SELECT citing.article_id as citing, lac_a.year, r.id_when_cited, cited_issue.country, citing.num_citations
FROM isi_lac_authored_articles as lac_a
JOIN isi_articles citing ON (lac_a.article_id = citing.article_id)
JOIN isi_citation_references r ON (citing.article_id = r.article_id)
JOIN isi_articles cited ON (cited.id_when_cited = r.id_when_cited)
JOIN isi_issues cited_issue ON (cited.issue_id = cited_issue.issue_id);
I have indexes on all the fields being JOINED on.
Is there anything I can do? My tables are large (some 1 Million records, the references tables has 500 million records, the articles table has 25 Million).
This is what EXPLAIN has to say:
+----+-------------+-------------+--------+--------------------------------------------------------------------------+---------------------------------------+---------+-------------------------------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+--------+--------------------------------------------------------------------------+---------------------------------------+---------+-------------------------------+---------+-------------+
| 1 | SIMPLE | cited_issue | ALL | NULL | NULL | NULL | NULL | 1156856 | |
| 1 | SIMPLE | cited | ref | isi_articles_id_when_cited,isi_articles_issue_id | isi_articles_issue_id | 49 | func | 19 | Using where |
| 1 | SIMPLE | r | ref | isi_citation_references_article_id,isi_citation_references_id_when_cited | isi_citation_references_id_when_cited | 17 | mimir_dev.cited.id_when_cited | 4 | Using where |
| 1 | SIMPLE | lac_a | eq_ref | PRIMARY | PRIMARY | 16 | mimir_dev.r.article_id | 1 | |
| 1 | SIMPLE | citing | eq_ref | PRIMARY | PRIMARY | 16 | mimir_dev.r.article_id | 1 | |
+----+-------------+-------------+--------+--------------------------------------------------------------------------+---------------------------------------+---------+-------------------------------+---------+-------------+
5 rows in set (0.07 sec)
If you realy need all the returned data, I would suggest two things:
You, probably, know the data better than MySQL and you can try to make advantage of it if MySQL is not correct in its assumptions. Currently, MySQL thinks that it is easier to full scan the whole isi_issues table at the beginning, and if the result is really going to include all issues, than the assumption is correct. But if there are many issues that should not be in the result, you may want to force another order of the joins that you consider more correct. It is you, who knows which table applies the strongest restrictions and which are the smallest to full scan (you will anyway need to full scan something, since there is no WHERE clause).
You can make profit from covering indexes (that is indexes that contain enough data in itself and not needing to touch the row data). For example, having an index (article_id, num_citations) on isi_articles and (article_id, year) on isi_lac_authored_articles and even (country) on isi_issues will significantly speed up that query as long as the indexes fit in memory, but, from the other side, will make you indexes larger and slightly slow dow inserts into the table.
i think it's the best you can do. i mean at least it's not using nested/multiple queries. you should do a little benchmark on the sql. you could at least limit your results at the least as possible. 15-30 rows for a return set is pretty fine per page (this depends on the app, but 15-30 for me is the tolerance range)
i believe in mySQL (phpMyAdmin, console, GUI whatever) they return some sort of "execution time" which is the time that it took to the query to process. compare that with a benchmark of the query using your server-side code. then compare that with the query run using the server-side code and outputting it with your app interface included after that.
by this, you can see where your bottle-neck is - that is where you optimize.
Unless the result of your query is input to some other query or system, it is useless to return that much(3M) rows. That would be clever to return just an acceptable amount of rows per query(like 1000) that is for visualizing.
Looking at your SQL - the lack of a WHERE clause means it is pulling all rows from:
JOIN isi_issues cited_issue ON (cited.issue_id = cited_issue.issue_id)
You could look at partitioning the large isi_issues table, this would allow MySQL to perform a bit quicker (smaller files are easier to handle)
Or alternatively you can loop the statement and use a LIMIT clause.
LIMIT 0,100000
then
LIMIT 100001, 200000
This will let the statements run quicker and you can deal with the data in batches.