如何使下面的查询在具有许多条件的查找中更有效

inkz8wg9  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(297)

首先,我需要一个分页功能,通过使用couplewhere条件限制以下查询查找中的结果。

SELECT SQL_CALC_FOUND_ROWS
    a.uid, b.NAME
FROM
    `profiles` AS a FORCE INDEX(profiles_country_city_gender_index)
JOIN `users` AS b
ON b.id = a.uid
AND a.country = 'INDONESIA'
AND a.gender = 0
JOIN (
    SELECT
        a.uid
    FROM
       profile_details AS a
    JOIN profile_details AS kids ON kids.uid = a.uid
    AND kids.kids_pref = 1
    JOIN profile_details AS current ON current.uid = a.uid
    AND current.current_relationship = 1
    JOIN profile_details AS smoking ON smoking.uid = a.uid
    AND smoking.smoking_pref = 1
    ) AS e ON e.uid = a.uid
AND ( TIMESTAMPDIFF( YEAR, a.birth_date, NOW()) BETWEEN 25 AND 35 )
LIMIT 33;

这里的所有表都是与表用户的一对一关系
配置文件
配置文件详细信息
在用户中使用id列作为主键,在其他表中使用uid作为外键。一开始,我对上面的查询/设计没有问题,直到表增长到300k行,查询运行需要 OK, Time: 0.726000s 我认为结果太慢了。
我尝试使用count(*)根据上述条件对行进行计数,并得到一些大致相同的结果,我需要有更快的方法从查找条件中获取行数,以使分页系统以更少的等待时间按预期工作。
正如您在查询中看到的,我正在使用:

FORCE INDEX(profiles_country_city_gender_index)

我认为,由于使用以下命令从作用域中产生较大的行,因此没有多大帮助:

AND a.country = 'INDONESIA' 
AND a.gender = 0

结果(148801行范围限制,按国家/地区,性别等于0),如果我与城市配对,这不是问题,查询时间是相当长的,因为行的结果要小得多,但当某一天有较大的行时,仍然会是一个问题。
任何可能要求解释问题的人:

Explain SELECT SQL_CALC_FOUND_ROWS
        a.uid, 
        b.NAME ...

Results:

| select_type | table   | type   | possible_keys                      | key                                | key_len | ref              | rows   | filtered  | Extra                              |
+-------------+---------+--------+------------------------------------+------------------------------------+---------+------------------+--------+-----------+------------------------------------+
| SIMPLE      | a       | ref    | profiles_country_city_gender_index | profiles_country_city_gender_index | 242     | const            | 148801 | 10.00     | Using index condition; Using where |
| SIMPLE      | a       | ref    | profile_details_uid_foreign        | profile_details_uid_foreign        | 3       | restfulapi.a.uid | 1      | 100.00.00 | Using index                        |
| SIMPLE      | kids    | ref    | profile_details_uid_foreign        | profile_details_uid_foreign        | 3       | restfulapi.a.uid | 1      | 10.00     | Using where                        |
| SIMPLE      | current | ref    | profile_details_uid_foreign        | profile_details_uid_foreign        | 3       | restfulapi.a.uid | 1      | 10.00     | Using where                        |
| SIMPLE      | smoking | ref    | profile_details_uid_foreign        | profile_details_uid_foreign        | 3       | restfulapi.a.uid | 1      | 10.00     | Using where                        |
| SIMPLE      | b       | eq_ref | PRIMARY                            | PRIMARY                            | 3       | restfulapi.a.uid | 1      | 100.00.00 |                                    |

正如您在explain result中看到的,没有表扫描或使用临时或使用范围,只有索引条件。我想,如果表中至少有100万行按国家范围返回,只要将时间与缩放行相乘30万就糟了:(。
下表定义有助于分析问题:

CREATE TABLE `profile_details` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `uid` mediumint(8) unsigned NOT NULL,
  `intents` tinyint(4) NOT NULL DEFAULT '3',
  `height` smallint(6) DEFAULT NULL,
  `body_type` tinyint(4) NOT NULL DEFAULT '5',
  `kids_pref` tinyint(4) NOT NULL DEFAULT '1',
  `drinking_pref` tinyint(4) NOT NULL DEFAULT '2',
  `living_with` tinyint(4) NOT NULL DEFAULT '0',
  `current_relationship` tinyint(4) NOT NULL DEFAULT '1',
  `sexual_pref` tinyint(4) NOT NULL DEFAULT '1',
  `smoking_pref` tinyint(4) NOT NULL DEFAULT '0',
  `status_online` tinyint(4) NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `profile_details_uid_foreign` (`uid`),
  KEY `idx_multipart` (`intents`,`body_type`,`kids_pref`,`drinking_pref`,`living_with`,`current_relationship`,`sexual_pref`,`smoking_pref`),
  CONSTRAINT `profile_details_uid_foreign` FOREIGN KEY (`uid`) REFERENCES `users` (`id`)
)

CREATE TABLE `profiles` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `uid` mediumint(8) unsigned NOT NULL,
  `birth_date` date NOT NULL,
  `gender` tinyint(4) NOT NULL DEFAULT '0',
  `country` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'ID',
  `city` varchar(60) COLLATE utf8mb4_unicode_ci DEFAULT 'Makassar',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `latitude` double NOT NULL DEFAULT '0',
  `longitude` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `profiles_uid_foreign` (`uid`),
  KEY `profiles_birth_date_index` (`birth_date`),
  KEY `profiles_latitude_longitude_index` (`latitude`,`longitude`),
  KEY `profiles_country_city_gender_index` (`country`,`city`,`gender`),
  KEY `idx_country_gender_birthdate` (`country`,`gender`,`birth_date`),
  KEY `idx_country_city_gender_birthdate` (`country`,`city`,`gender`,`birth_date`),
  CONSTRAINT `profiles_uid_foreign` FOREIGN KEY (`uid`) REFERENCES `users` (`id`)
)

如何找到解决方案,是否需要重新设计表格以获得理想的系统?也许这是最后的选择。
编辑
我正在尝试你之前的建议,首先我在三列中添加了一个索引:

CREATE INDEX profiles_country_gender_birth_date_index on `profiles`(country,gender,birth_date);

我试图选择count(*)而不与profile\u detail连接:

SELECT
    count(*)

FROM
    `profiles` AS a 
    FORCE INDEX ( profiles_country_gender_birth_date_index )
    JOIN `users` AS b ON b.id = a.uid 
and 
a.country = 'INDONESIA' 

    AND a.gender =1 
    AND a.birth_date BETWEEN NOW()- INTERVAL 35 YEAR 
    AND NOW()- INTERVAL 25 YEAR

结果计时在0.7秒到0.35秒之间不稳定,我不知道为什么会这样。下面以json格式解释查询计划,以帮助找出罪魁祸首。

{
  "query_block": {
    "select_id": 1,
    "cost_info": {
      "query_cost": "114747.38"
    },
    "nested_loop": [
      {
        "table": {
          "table_name": "a",
          "access_type": "range",
          "possible_keys": [
            "profiles_country_gender_birth_date_index"
          ],
          "key": "profiles_country_gender_birth_date_index",
          "used_key_parts": [
            "country",
            "gender",
            "birth_date"
          ],
          "key_length": "246",
          "rows_examined_per_scan": 94066,
          "rows_produced_per_join": 32961,
          "filtered": "100.00",
          "index_condition": "((`restfulapi`.`a`.`gender` = 1) and (`restfulapi`.`a`.`country` = 'INDONESIA') and (`restfulapi`.`a`.`birth_date` between <cache>((now() - interval 35 year)) and <cache>((now() - interval 25 year))))",
          "cost_info": {
            "read_cost": "15858.00",
            "eval_cost": "6592.23",
            "prefix_cost": "75194.00",
            "data_read_per_join": "16M"
          },
          "used_columns": [
            "uid",
            "birth_date",
            "gender",
            "country"
          ]
        }
      },
      {
        "table": {
          "table_name": "b",
          "access_type": "eq_ref",
          "possible_keys": [
            "PRIMARY"
          ],
          "key": "PRIMARY",
          "used_key_parts": [
            "id"
          ],
          "key_length": "3",
          "ref": [
            "restfulapi.a.uid"
          ],
          "rows_examined_per_scan": 1,
          "rows_produced_per_join": 32961,
          "filtered": "100.00",
          "using_index": true,
          "cost_info": {
            "read_cost": "32961.15",
            "eval_cost": "6592.23",
            "prefix_cost": "114747.38",
            "data_read_per_join": "89M"
          },
          "used_columns": [
            "id"
          ]
        }
      }
    ]
  }
}
n9vozmp4

n9vozmp41#

INDEX(country, gender, birth_date)  -- in this order

并改变 birth_date “可销售”:

AND  ( TIMESTAMPDIFF( YEAR, a.birth_date, NOW()) BETWEEN 25 AND 35 )

AND a.birth_date BETWEEN NOW() - INTERVAL 35 YEAR
                     AND NOW() - INTERVAL 25 YEAR

这样优化器就可以使用 birth_date . LIMIT 33 --你在乎哪33排吗?也许你需要一个 ORDER BY ?
不要这样做 JOIN ( SELECT ... profile_details ... ) 当一个计划 JOIN profile_details ... 会有用的。 SQL_CALC_FOUND_ROWS 代价不菲。把它取下来看看它走得有多快,然后决定是否值得保留。
我不认为你需要 JOIN profile_details 不止一次,尤其是因为它与 profiles .
我的意思是:
而不是 JOIN ( SELECT ... ) 刚刚

JOIN  profile_details AS d  USING(uid)

然后将这些添加到where子句中:

AND  d.kids_pref = 1
AND  d.current_relationship = 1
AND  d.smoking_pref = 1

避免文件排序

INDEX(country, gender,   -- Tested with '='
      birth_date,        -- Tested as a "range"
      uid)               -- For the ORDER BY -- Useless!

建立索引时,请按以下顺序包括列
所有列测试为“列=常量”。
一个范围(例如 BETWEEN ). 如果这和 ORDER BY 那么就可能避免使用“文件排序”。
如果没有“范围” WHERE ,那么
所有列测试为“列=常量”。
这个 ORDER BY 列--假设它们都是 DESC 或全部 ASC (或者,在mysql 8.0中,匹配 INDEX 定义)。这可能会避免“文件排序”。
但是索引不能同时处理“range”和不同的“order by”。考虑以下几点。你有一个姓和名的人的名单。查询结果是

SELECT ...
    WHERE last_name LIKE 'Ja%'   -- a "range"
    ORDER BY first_name;
``` `INDEX(last_name, first_name)` 会有助于 `WHERE` ,但是把名字弄乱了。反之亦然。
(这是一种简化,参见http://mysql.rjweb.org/doc.php/index_cookbook_mysql 更多细节。)

相关问题