Note that there are some explanatory texts on larger screens.

plurals
  1. POGROUP BY Optimization
    primarykey
    data
    text
    <p>Hey. I´ve got these two tables in a 1:n relation.</p> <pre><code>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 ; </code></pre> <p>and</p> <pre><code>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 ; </code></pre> <p>A location could be placed in more than one category.</p> <p>For example:</p> <p>Location: "Pizza Hut" Categories: "Italian Food", "Fast Food"</p> <p>These categories are child categories of the parent category food.</p> <p>Now I want to select all the locations within the category food.</p> <pre><code>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 </code></pre> <p>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 …</p> <p>Have I got to add another index? Or is anything wrong with my scheme? How would you solve this problem? Thanks a lot.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload