MySQL - 选择具有嵌套'WHERE'的字段

时间:2017-02-24 23:38:21

标签: mysql 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行,其中已经应用了一种不可见的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子句,所以我试图确定是否有办法“嵌套”这个。

1 个答案:

答案 0 :(得分:0)

您可能只需要条件聚合

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')所以我可能没有这么做,并且没有聚合的group by子句是没有意义的。