Sub-query 子查询

WHERE 子查询

SELECT 
	-- Select the date, home goals, and away goals scored
    date,
	home_goal,
	away_goal
FROM  matches_2013_2014
-- Filter for matches where total goals exceeds 3x the average
WHERE (home_goal + away_goal) > 
       (SELECT 3 * AVG(home_goal + away_goal)
        FROM matches_2013_2014); 

FROM子查询

SELECT
	-- Select country name and the count match IDs
    c.name AS country_name,
    COUNT(sub.id) AS matches
FROM country AS c
-- Inner join the subquery onto country
-- Select the country id and match id columns
INNER JOIN (SELECT country_id, id 
           FROM match
           -- Filter the subquery by matches with 10+ goals
           WHERE (home_goal + away_goal) >= 10) AS sub
ON c.id = sub.country_id
GROUP BY country_name;
  1. 可以看做:SELECT FROM country 的结果INNER JOIN 子查询表
  2. county表和sub表用c.id连接,c.id只需要在country表中存在即可,不需要出现在最终的select结果中
SELECT
	-- Select country, date, home, and away goals from the subquery
    country,
    date,
    home_goal,
    away_goal
FROM 
	-- Select country name, date, and total goals in the subquery
	(SELECT name AS country, 
     	    m.date, 
     		m.home_goal, 
     		m.away_goal,
           (m.home_goal + m.away_goal) AS total_goals
    FROM match AS m
    LEFT JOIN country AS c
    ON m.country_id = c.id) AS subq
-- Filter by total goals scored in the main query
WHERE total_goals >= 10;
  1. FROM后的子查询为一个整体,区别上面的例子;
  2. 最终的筛选条件是WHERE total_goals >= 10,虽然total_goals没有出现在SELECT的结果中,但是from ()AS subq的一个字段,也ok

SELECT 子查询

SELECT 
	l.name AS league,
    -- Select and round the league's total goals
    ROUND(AVG(m.home_goal + m.away_goal), 2) AS avg_goals,
    -- Select & round the average total goals for the season
    (SELECT ROUND(AVG(home_goal + away_goal), 2) 
     FROM match
     WHERE season = '2013/2014') AS overall_avg
FROM league AS l
LEFT JOIN match AS m
ON l.country_id = m.country_id
-- Filter for the 2013/2014 season
WHERE season = '2013/2014'
  1. 主查询中的ROUND(AVG(m.home_goal + m.away_goal), 2) AS avg_goals是每个league的avg goal;
  2. 子查询的目的是:计算整个dataset的平均值,不考虑子查询外的限制条件
    在这里插入图片描述

子查询Everywhere

SELECT 
	-- Select the stage and average goals from s
	s.stage,
    ROUND(s.avg_goals,2) AS avg_goal,
    -- Select the overall average for 2012/2013
    (SELECT AVG(home_goal + away_goal) FROM match WHERE season = '2012/2013') AS overall_avg
FROM 
	-- Select the stage and average goals in 2012/2013 from match
	(SELECT
		 stage,
         AVG(home_goal + away_goal) AS avg_goals
	 FROM match
	 WHERE season = '2012/2013'
	 GROUP BY stage) AS s
WHERE 
	-- Filter the main query using the subquery
	s.avg_goals > (SELECT AVG(home_goal + away_goal) 
                    FROM match WHERE season = '2012/2013');

WHERE和SELECT语句中出现子查询:
(SELECT AVG(home_goal + away_goal)
FROM match WHERE season = ‘2012/2013’)
都是为了计算overall AVG =》 不受到stage的影响下

使用多个subquery要注意

每个子查询都要filter上 where necessary
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Cecilia_W422/article/details/88602629
今日推荐