I'm building a twitter app that displays posted links on twitter, but I have a problem when sorting the table by time.
tweet
+----------------------------------------+
| tweet_id | [...] | created_at |
+----------------------------------------+
| 123456 | [...] | 2012-06-11 11:31:28 |
| 234567 | [...] | 2012-06-11 11:32:55 |
| 345678 | [...] | 2012-06-11 11:33:22 |
+----------------------------------------+
tweets_url
+---------------------+
| tweet_id | url |
+---------------------+
| 123456 | cnn.com |
| 123456 | fox.com |
| 234567 | abc.com |
| 345678 | abc.com |
+---------------------+
Heres my SQL (I'm using GROUP by to return only unique URLS):
SELECT tweet_urls.url,
FROM `tweets`
LEFT JOIN tweet_urls ON tweet_urls.tweet_id = tweets.tweet_id
WHERE tweet_urls.url LIKE '%cnn.com%'
GROUP BY tweet_urls.url
ORDER BY tweets.created_at DESC LIMIT 0 , 20
I tried different variations of running this query with outer select from here, using different joins and inner SELECTS.
Edit: I've done some further testing. It seems that Mysql creates a temporary table based on the GROUP BY tweet_urls.url and then orders the results w/o using the specified index because it is run on a temp table.
Here's the EXPLAIN output:
+----+-------------+------------+--------+---------------+---------+---------+-----+----------------------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+---------------------------------------------------------------------------------------------------------+----------------------------------------------+
| 1 | SIMPLE | tweet_urls | index | tweet_id | url | 422 | NULL 86783 | Using where; Using temporary; Using filesort
| 1 | SIMPLE | tweets | eq_ref | PRIMARY | PRIMARY | 8 | tweet_urls.tweet_id |
+----+-------------+------------+--------+---------------+---------+---------+-----+----------------------+----------------------------------------------+