[MySQL] Execution order optimization query of MySQL join table query

SELECT t4.orgName,
                   t3.projectName,
                   t3.Partner,
                   t1.type,
                   COUNT(DISTINCT t1.imei) AS count
            FROM `t_teminal` AS t1
            LEFT JOIN `t_orgcode_orgid_rela` AS t2
              ON t1.orgid = t2.orgId
            LEFT JOIN `t_org_code` AS t3
            ON t2.topOrganizationCode = t3.topOrganizationCode
            LEFT JOIN `t_organization` AS t4
            ON t1.orgid = t4.orgId
            GROUP BY t1.orgid

The join table query will involve the operation of multiple tables, and the utilization of the index will be limited. The execution time of the above command is 720s

Taking the above example, because the join table queries are all run in parallel, the index of the t1 table is invalid. The t1 table is the largest table with about 500,000 rows of data, while the other tables are only a few hundred rows of configuration information tables.

The index of the t1 table is the key to performance.

In order to use the index of the t1 table, use a subquery, execute t1 first, and then match the information. 

This kind of thinking should be helpful for various business-oriented report queries, because it is necessary to output human-friendly results.

The following command execution time is 3.6s

SELECT
	t4.orgName,
	t3.projectName,
	t3.Partner,
	t1.type,
	t1.count
FROM
	(
		SELECT
			orgid,
			type,
			COUNT(DISTINCT imei) AS count
		FROM
			`t_teminal`
		GROUP BY
			orgid
	) AS t1
LEFT JOIN `t_orgcode_orgid_rela` AS t2 ON t1.orgid = t2.orgId
LEFT JOIN `t_org_code` AS t3 ON t2.topOrganizationCode = t3.topOrganizationCode
LEFT JOIN `t_organization` AS t4 ON t1.orgid = t4.orgId

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325501235&siteId=291194637