Home » Performance » MySQL » COUNT, SUM, ORDER and 2xJOINS
COUNT, SUM, ORDER and 2xJOINS [message #3332] Tue, 22 July 2008 21:57 Go to next message
mbor  is currently offline mbor
Messages: 2
Registered: July 2008
Junior Member
hi,

I'm noob but still lerning so can you help me with this?

I have res_item table with articles (about 200k rows), fa_user table with authors, notes (users can vote for articles, note is sum( no_note ) and comments table (I want to show number of comments count( co_id )).
Aricles have to be ordered by it_id DESC.

My query:
SELECT i . * , note_sum, comments_count, u.user_name
FROM (
`res_item` i
)
INNER JOIN `fa_user` u ON i.it_us_id = u.id
LEFT JOIN (

SELECT no_it_id, sum( no_note ) AS note_sum
FROM notes
GROUP BY no_it_id
)n ON n.no_it_id = i.it_id
LEFT JOIN (

SELECT co_it_id, count( co_id ) AS comments_count
FROM comments
GROUP BY co_it_id
)co ON co.co_it_id = i.it_id
ORDER BY it_id DESC
LIMIT 10 


92.0550 s Sad

The query EXPLAIN
id  	 select_type  	 table  	 type  	 possible_keys  	 key  	 key_len  	 ref  	 rows  	 Extra
1 	PRIMARY 	i 	ALL 	NULL 	NULL 	NULL 	NULL 	182850 	Using temporary; Using filesort
1 	PRIMARY 	u 	eq_ref 	PRIMARY 	PRIMARY 	4 	podajcegle_2.i.it_us_id 	1 	Using where
1 	PRIMARY 	<derived2> 	ALL 	NULL 	NULL 	NULL 	NULL 	2 	 
1 	PRIMARY 	<derived3> 	ALL 	NULL 	NULL 	NULL 	NULL 	1 	 
3 	DERIVED 	comments 	ALL 	NULL 	NULL 	NULL 	NULL 	4 	Using temporary; Using filesort
2 	DERIVED 	notes 	ALL 	NULL 	NULL 	NULL 	NULL 	2 	Using temporary; Using filesort


without ORDER BY everything is good, 0.27s

Re: COUNT, SUM, ORDER and 2xJOINS [message #3333 is a reply to message #3332 ] Tue, 22 July 2008 23:22 Go to previous message
teajay2  is currently offline teajay2
Messages: 9
Registered: July 2008
Location: new york, ny
Junior Member
Hey,

Since you are only looking to return 10 queries, it might be better to do a subquery rather then the joins.

For example:


select i.*, u.user_name,
(select sum(1) from notes n where n.no_it_id = i.it_id) as note_sum,
(select count(1) from comments c where c.co_it_id = i.it_id) as comments_count
from res_item i
join fa_user u on i.it_us_id = u.id
order by i.it_id desc


In addition, you might wanna add indexes, such as on the following columns:
notes - no_it_id
comments - co_it_id
fa_user - it_us_id

You can play with adding an index to 'it_id' on the res_item table, but I don't think its going to do much since its not used in the where clause anywhere.

-T

[Updated on: Tue, 22 July 2008 23:26]

Previous Topic:How to optimize this query?
Next Topic:MySQL5 Repliction seconds slower
Goto Forum:
  



Current Time: Thu Nov 20 19:34:07 EST 2008

Total time taken to generate the page: 0.04041 seconds
.:: Contact :: Home :: MySQL Support by Percona.com ::.

Powered by: FUDforum 2.7.5.
Copyright ©2001-2006 FUD Forum Bulletin Board Software

MySQL Performance | Forum authority Badge