Query:
SELECT DISTINCT `announcements`.* FROM `announcements`
LEFT JOIN `ann_categories` ON `announcements`.`ann_cat_id` = `ann_categories`.`id`
LEFT JOIN `ann_subcategories` ON `announcements`.`ann_sub_cat_id` = `ann_subcategories`.`id`
LEFT JOIN `ann_features_values` ON `announcements`.`id` = `ann_features_values`.`ann_id`
WHERE `disabled` = 0
ORDER BY `date_added` DESC
LIMIT 15
The run time is more than 3 seconds.
The Explain shows:
+----+-------------+---------------------+--------+--------------------------------------+--------------------------------------+---------+--------------------------------------------+-------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------------+--------+--------------------------------------+--------------------------------------+---------+--------------------------------------------+-------+----------------------------------------------+
| 1 | SIMPLE | announcements | ref | disabled date_added_disabled | disabled | 1 | const | 50390 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | ann_categories | eq_ref | PRIMARY | PRIMARY | 2 | torgobmen_new.announcements.ann_cat_id | 1 | Using index; Distinct |
| 1 | SIMPLE | ann_subcategories | eq_ref | PRIMARY | PRIMARY | 2 | torgobmen_new.announcements.ann_sub_cat_id | 1 | Using index; Distinct |
| 1 | SIMPLE | ann_features_values | ref | FK_ann_features_values_announcements | FK_ann_features_values_announcements | 5 | torgobmen_new.announcements.id | 4 | Using index; Distinct |
+----+-------------+---------------------+--------+--------------------------------------+--------------------------------------+---------+--------------------------------------------+-------+----------------------------------------------+
4 rows in set (0.00 sec)
This request generated Yii2 and do not understand the meaning of all joynow in this query...
The code in the controller (used ActiveQuery):
$announcements = Announcements::find()
->joinWith('annCat')
->joinWith('annSubCat')
->joinWith('annFeaturesValues')
->where("disabled` = 0');
->orderBy(['date_added' => SORT_DESC])
->limit(15)->distinct()->asArray()->all();
As a result, I get the array $announcements which has data from related tables. (annCat, annSubCat... links that are in the models). Everything is working "right", but 3 seconds to execute - a lot...
It turns out you choose a unique row not by any indexed field, and a string with all the data from announcements. Of course have them all sort out to sort.
If you need all data from all tables, you need to do GROUP BY for a particular indexed field of repetitions you want to avoid
Like that:
- elena_Decko commented on June 10th 19 at 17:08