好时光!告诉我如何优化这个查询,如果可能的话,将其合并为一个!
$query = "SELECT external_source_id FROM smf_tds_unique_statistic WHERE ".$dateRange." GROUP BY external_source_id ORDER BY external_source_id ASC;";
$query .= "SELECT sources_id FROM smf_tds_unique_statistic WHERE ".$dateRange." GROUP BY sources_id ORDER BY sources_id ASC;";
$query .= "SELECT ip_country FROM smf_tds_unique_statistic WHERE ".$dateRange." GROUP BY ip_country ORDER BY ip_country ASC;";
$query .= "SELECT cidr FROM smf_tds_unique_statistic WHERE ".$dateRange." GROUP BY cidr ORDER BY cidr ASC;";
if (mysqli_multi_query($db, $query)) {
do {
if ($result = mysqli_store_result($db)) {
while ($row = mysqli_fetch_row($result)) {
$val = $row[0];
if ($val != '') {
$options .= '<li class="select_input_option_item" value="'.$val.'">'.$val.'</li>';
}
}
array_push($optionsArr, $options);
$options = '';
mysqli_free_result($result);
}
if (!mysqli_more_results($db)) break;
} while (mysqli_next_result($db));} mysqli_close($db);
实际上,每个查询都有不同的分组依据和排序依据,因此最好的选择是使用
UNION
$query = <<<QRY
SELECT external_source_id as ID
FROM smf_tds_unique_statistic
WHERE $dateRange
GROUP BY external_source_id
ORDER BY external_source_id ASC
UNION
SELECT sources_id ID
FROM smf_tds_unique_statistic
WHERE $dateRange
GROUP BY sources_id
ORDER BY sources_id ASC
UNION
SELECT ip_country ID
FROM smf_tds_unique_statistic
WHERE $dateRange
GROUP BY ip_country
ORDER BY ip_country ASC
UNION
SELECT cidr ID
FROM smf_tds_unique_statistic
WHERE $dateRange
GROUP BY cidr
ORDER BY cidr ASC
QRY;
你应该明白了。另一种方法是使用日期过滤器一次并创建一个索引
TEMP
表并在您的 UNION 中使用它。取决于有多少记录以及 $dateRange
过滤器的价格
看来您的查询只需要获取四列中不同值的列表。
这里有一种方法可以通过一个查询来完成此操作:
SELECT
GROUP_CONCAT(DISTINCT external_source_id ORDER BY external_source_id) AS external_source_id,
GROUP_CONCAT(DISTINCT sources_id ORDER BY sources_id) AS sources_id,
GROUP_CONCAT(DISTINCT ip_country ORDER BY ip_country) AS ip_country,
GROUP_CONCAT(DISTINCT cidr ORDER BY cidr) AS cidr
FROM smf_tds_unique_statistic
WHERE $dateRange
这些值将在单行中返回,每列将包含一个字符串,该字符串是数据库中每个相应列的不同值的逗号分隔列表。您必须使用 PHP explode() 将每个字符串转换为数组。
优化此查询的唯一方法是为要使用的
$dateRange
条件创建索引。但是您没有在问题中包含 $dateRange
的值,所以我将留给您来解决这个问题。