我注意到 View 和生成该视图的基础 Select 语句之间的性能差异。
创建视图时,它会对所有基础表(大约 700 万行)进行表扫描,但 Select 语句不会进行这样的扫描。
有人可以解释为什么可能会有所不同吗?以及如何使 View 像 Select 语句一样执行?
可以在 Google 表格中找到两个查询的解释计划:链接
Select 语句:更新:我已将问题缩小到以下 Select 语句。看起来 Group By 或 Group Concat 可能会导致问题。
SELECT
-- IOHD_REQUEST fields
r.ID as requestIdMultiple
-- KEYVALUE and MULTIPLE fields
, CAST(GROUP_CONCAT(kv6.VALUE)AS CHAR(255)) AS CLIENT_ID
, CAST(GROUP_CONCAT(kv1.VALUE) AS CHAR(255)) AS IDENTIFIER_ID
, CAST(GROUP_CONCAT(ri.IDENTIFIER) AS CHAR(255)) AS IDENTIFIER
, CAST(GROUP_CONCAT(kv7.VALUE) AS CHAR(255)) AS PLATFORM_ID
, CAST(GROUP_CONCAT(kv8.VALUE) AS CHAR(255)) AS VENDOR_ID
FROM IOHD_REQUEST r
LEFT JOIN IOHD_REQUEST_HELPDESK rh ON r.ID = rh.REQUEST_ID
LEFT JOIN IOHD_REQUEST_CLIENT rc ON r.ID = rc.REQUEST_ID
LEFT JOIN IOHD_REQUEST_IDENTIFIER ri ON r.ID = ri.REQUEST_ID
LEFT JOIN IOHD_REQUEST_PLATFORM rp ON r.ID = rp.REQUEST_ID
LEFT JOIN IOHD_REQUEST_VENDOR rv ON r.ID = rv.REQUEST_ID
LEFT JOIN IOHD_REF_KEYVALUE kv1 ON (ri.IDENTIFIER_ID = kv1.KEY AND kv1.TYPE = 'IDENTIFIERTYPE')
LEFT JOIN IOHD_REF_KEYVALUE kv6 ON (rc.CLIENT_ID = kv6.KEY AND kv6.TYPE = 'CLIENT')
LEFT JOIN IOHD_REF_KEYVALUE kv7 ON (rp.PLATFORM_ID = kv7.KEY AND kv7.TYPE = 'PLATFORM')
LEFT JOIN IOHD_REF_KEYVALUE kv8 ON (rv.VENDOR_ID = kv8.KEY AND kv8.TYPE = 'VENDOR')
GROUP BY r.ID;
在视图的解释计划中让我失望的线如下。计划中的所有后续行在视图和选择语句之间都是相同的:
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 PRIMARY <derived2> NULL ALL NULL NULL NULL NULL 7237546 100 NULL
指数
--
-- Indexes for table `IOHD_REF_KEYVALUE`
--
ALTER TABLE `IOHD_REF_KEYVALUE`
ADD PRIMARY KEY (`ID`),
ADD KEY `TYPE` (`TYPE`,`KEY`);
--
-- Indexes for table `IOHD_REQUEST`
--
ALTER TABLE `IOHD_REQUEST`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `IOHD_REQUEST_CLIENT`
--
ALTER TABLE `IOHD_REQUEST_CLIENT`
ADD PRIMARY KEY (`ID`),
ADD KEY `REQUEST_ID` (`REQUEST_ID`);
--
-- Indexes for table `IOHD_REQUEST_HELPDESK`
--
ALTER TABLE `IOHD_REQUEST_HELPDESK`
ADD PRIMARY KEY (`ID`),
ADD KEY `REQUEST_ID` (`REQUEST_ID`);
--
-- Indexes for table `IOHD_REQUEST_IDENTIFIER`
--
ALTER TABLE `IOHD_REQUEST_IDENTIFIER`
ADD PRIMARY KEY (`ID`),
ADD KEY `REQUEST_ID` (`REQUEST_ID`);
--
-- Indexes for table `IOHD_REQUEST_PLATFORM`
--
ALTER TABLE `IOHD_REQUEST_PLATFORM`
ADD PRIMARY KEY (`ID`),
ADD KEY `REQUEST_ID` (`REQUEST_ID`);
--
-- Indexes for table `IOHD_REQUEST_VENDOR`
--
ALTER TABLE `IOHD_REQUEST_VENDOR`
ADD PRIMARY KEY (`ID`),
ADD KEY `REQUEST_ID` (`REQUEST_ID`);