[英]Indexing Query In MySql Workbench
我需要編寫一個涉及子查詢的查詢並進行索引。 因此,我想出一個查詢來查找一年內組建速度最快的團隊名稱:
SELECT CONCAT(team_long_name, ',', team_short_name) AS TeamName,
EXTRACT(YEAR FROM date) AS Year,
buildUpPlaySpeed
FROM team JOIN
team_attributes
ON team.team_api_id = team_attributes.team_api_id
WHERE
(buildUpPlaySpeed,team_attributes.date) in (SELECT
MAX(buildUpPlaySpeed),team_attributes.date
FROM team_attributes
WHERE team_attributes.date = team_attributes.date
group by team_attributes.date)
ORDER BY date desc;
索引顯示在date,team_api_id,buildUpPlaySpeed列上。
關於如何進一步降低成本的任何建議?
是。 用聯接替換相關的子查詢:
SELECT CONCAT (
team_long_name
,','
,team_short_name
) AS TeamName
,EXTRACT(YEAR FROM [DATE]) AS Year
,buildUpPlaySpeed
FROM team
INNER JOIN team_attributes ON team.team_api_id = team_attributes.team_api_id
INNER JOIN (
SELECT MAX(buildUpPlaySpeed) maxbuildup
,team_attributes.[DATE]
FROM team_attributes
WHERE team_attributes.[DATE] = team_attributes.DATE
GROUP BY team_attributes.[DATE]
) x ON buildUpPlaySpeed = x.maxbuildup
AND team_attributes.DATE = x.[DATE]
ORDER BY [DATE] DESC
;
並且,出於理智的考慮,請不要將列“ date”命名為SQL所使用的列。 非常混淆。
也試試這個
SELECT CONCAT(team_long_name,',',team_short_name) AS TeamName,EXTRACT(YEAR FROM DATE) AS Year,buildUpPlaySpeed
FROM team
INNER JOIN team_attributes ON team.team_api_id = team_attributes.team_api_id
INNER JOIN ( SELECT MAX(buildUpPlaySpeed) maxbuildup,team_attributes.DATE FROM team_attributes
WHERE team_attributes.DATE = team_attributes.DATE
GROUP BY team_attributes.DATE ) t1
where buildUpPlaySpeed = t1.maxbuildup AND team_attributes.DATE = t1.DATE ORDER BY DATE DESC;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.