views:

355

answers:

1

Hey. I´ve got these two tables in a 1:n relation.

CREATE TABLE IF NOT EXISTS `de_locations` (
`id` int(11) NOT NULL auto_increment,
`user_id` int(11) default NULL,
`author_id` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`district_id` int(11) NOT NULL,
`title` varchar(150) collate utf8_unicode_ci NOT NULL,
`description` tinytext collate utf8_unicode_ci,
`lat` double NOT NULL,
`lng` double NOT NULL,
`stars` double default '0',
`comments` mediumint(9) default '0',
`flag` tinyint(4) default '0',
PRIMARY KEY  (`id`),
KEY `user_id` (`user_id`),
KEY `flag` (`flag`),
KEY `rating_district` (`district_id`,`stars`,`comments`),
KEY `rating_city` (`city_id`,`stars`,`comments`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=15 ;

and

CREATE TABLE IF NOT EXISTS `de_location2category` (
`id` int(11) NOT NULL auto_increment,
`location_id` int(11) NOT NULL,
`cat_id` mediumint(9) NOT NULL,
PRIMARY KEY  (`id`),
UNIQUE KEY `rel` (`location_id`,`cat_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=14 ;

A location could be placed in more than one category.

For example:

Location: "Pizza Hut" Categories: "Italian Food", "Fast Food"

These categories are child categories of the parent category food.

Now I want to select all the locations within the category food.

SELECT a.id, a.title, a.description, a.street, a.hnr, ROUND(a.stars) as stars, a.comments, a.lat, a.lng
FROM de_locations as a 
INNER JOIN de_location2category as b
ON b.location_id = a.id
WHERE b.cat_id BETWEEN 0 AND 100 
AND a.city_id = 1000 
GROUP BY a.id
ORDER BY a.stars DESC, a.comments DESC

I need the GROUP BY because I don´t want duplicate locations if they where related to more than one category. But this query builds an temporary table and uses filesort. If I leave the GROUP BY everything is fine, but I need it …

Have I got to add another index? Or is anything wrong with my scheme? How would you solve this problem? Thanks a lot.

A: 

Why not just use DISTINCT a.id ?

Amber
same result as GROUP BY: temporary tables and filesort
split
Yes, that's pretty much a given since you're sorting by multiple keys. It's just that DISTINCT describes what you're actually trying to achieve far better then GROUP BY.
Amber
Do I got you right that the problem is that I use the index "rel" in the WHERE clause and the index "rating_city" in the ORDER BY clause?And because of that I didn´t have a chance to only change the index? So I have to live with temporary tables and filesort?Sorry, got some language problems ...
split