MySQL - Select 嵌套字段 'WHERE'

MySQL - Select Field With Nested 'WHERE'

我正在处理一个使用 SUM 命令获取多个值的项目。现在,所有这些工作正常,但在加载时间方面存在问题,因为查询需要 3.4 秒才能完成。

这是我目前所拥有的示例:

SELECT
p.`player_id`,
p.`player_name` AS `name`,
d.`player_debut` AS `debut`,
SUM(a.`player_order` <= '11' OR a.`player_sub` != '0') AS `apps`,
SUM(a.`player_order` <= '11') AS `starts`,
SUM(a.`player_goals`) AS `goals`
FROM
`table1` r,
`table2` a,
`table3` p
LEFT JOIN `table4` d ON p.`player_id` = d.`player_id`
WHERE
r.`match_id` = a.`match_id` AND
a.`player_id` = p.`player_id` AND
r.`void` = '0'
GROUP BY
a.`player_id`
ORDER BY
p.`player_name` ASC

注意第 4 行。该字段是通过在查询的下方使用 LEFT JOIN 来检索的。通过去掉这两条线,加载时间减少到不到 0.5 秒——一个显着的改进。

我试图在那里(第 4 行)实现的是与第 5-7 行类似的东西(第 4 行),其中应用了一种不可见的 WHERE 子句。

我的想法是 t4.date WHERE t2.order <= '14',但我不确定如果没有前面提到的 LEFT JOIN 和随之而来的加载时间增加,我将如何实现它。

为澄清起见,以下是 table4 的创建方式 - 将以下查询转换为 VIEW。

SELECT a.`player_id`, m.`date` AS `player_debut`
FROM
`table1` r,
`table2` a,
`table3` p
WHERE
a.`match_id` = m.`match_id` AND
a.`player_id` = p.`player_id` AND
m.`match_void` = '0' AND
(
    a.`player_order` BETWEEN '1' AND '11' OR
    a.`player_sub_on_for` != '0'
)
GROUP BY p.`player_id`
ORDER BY p.`player_name` ASC

本质上,因为我对两个查询使用相同的表并且只使用不同的 WHERE 子句,所以我试图确定是否有办法 'nest' 这个。

您可能只需要条件聚合

SELECT p.`player_id`, p.`player_name` AS `name`, 
min(case when a.player_order   <= '11' OR a.`player_sub` != '0' then r.date else  0 end) `debut`,
SUM(case when a.`player_order` <= '11' OR a.`player_sub` != '0' then 1 else  0 end) AS `apps`,
SUM(case when a.`player_order` <= '11' then 1 else 0 end) AS `starts`,
SUM(a.`player_goals`) AS `goals`
FROM
`table1` r,
left join `table2` a on r.`match_id` = a.`match_id`,
left join `table3` p on a.`player_id` = p.`player_id`
WHERE  r.`void` = '0'
GROUP BY p.player_id,a.`player_id`
ORDER BY p.player_id,p.`player_name`;

您的列名似乎有些不一致 (a.player_sub,a.player_sub_on_for,m.match_void,r.void = '0 ') 所以我可能不太正确,没有聚合的按子句分组是没有意义的。