innerjoinon加条件和where加条件_SQL学习笔记-
GROUPBYJOINUNION
最近在DataCamp上学习SQL(基于PostgreSQL)的课程,本⽂主要记录⾃⼰易记混的点,以便⽇后参考学习,不做原理讲解。
GROUP BY(分组)⼀般和聚合函数⼀起使⽤,包括COUNT(),AVG(),MAX(),MIN(),SUM();⼀般跟在FROM后⾯;
1. GROUP BY(分组)
SELECT语句中未出现在聚合函数⾥的列都要出现在GROUP BY。
WHERE/ GROUP BY/ HAVING/ ORDER BY 执⾏顺序
2. WHERE/ GROUP BY/ HAVING/ ORDER BY 执⾏顺序
SELECT
⾸先WHERE将最原始记录中不满⾜条件的记录删除(所以应该在where语句中尽量将不符合条件的记录
筛选掉,这样可以减少分组的次数),WHERE语句不能⽤聚合函数
group by的用法及原理详解WHERE语句不能⽤聚合函数;
然后通过GROUP BY关键字对数据进⾏分组 ;
接着根据HAVING关键字后⾯指定的筛选条件,将分组后不满⾜条件的记录筛选掉,(HAVING可以⽤聚合函数,如 HAVING AVG(col) > 10;
最后按照ORDER BY语句进⾏排序。
WHER⼦句在聚合前先筛选记录,也就是说作⽤在GROUP BY和 HAVING⼦句前;⽽HAVING⼦句在聚合后对组记录进⾏筛选。
JOIN
3. JOIN
INNER JOIN / JOIN : only includes records in which the key is is both tables.
INNER JOIN / JOIN
LEFT JOIN:keeps all of the records in the left table while bringing in missing values for those key field values that don't LEFT JOIN:
appear in the right table.
RIGHT JOIN:keeps all of the records in the right table while bringing in missing values for those key field values that don't RIGHT JOIN
appear in the left table.
FULL JOIN:combines a LEFT JOIN and a RIGHT JOIN, it will bring in all records from both the left and the right table and FULL JOIN
keep all of the missing values accordingly.
当⽤于联结两个表的字段相同时,USING等价于JOIN操作中的ON,如以下2个实例等价:
SELECT a.name, b.age FROM test AS a
JOIN test2 AS b
ON a.id = b.id;
等价于
SELECT a.name, b.age
FROM test AS a
JOIN test2 AS b
USING(id);
注:细微区别在与,USING(id) 在结果集中只会有⼀个id列。
UNION
4. UNION
DOES NOT double count those that are in both tables.(包含两个表中的每UNION:includes every record in both tables but DOES NOT
UNION
个记录,但重复的⾏,最终只会出现⼀次)
UNION ALL:includes every record in both tables and DOES replicate those are in bot tables.(包括两个表中的每个记录,并且UNION ALL
保留重复⾏)
INTERSECT:results in only those records found in both of the tow tables.(交集,两个集中共同的部分)
INTERSECT
EXCEPT:results in only those records in one table BUT NOT the other.(差异,两个集中不重复的部分)
EXCEPT
你的点赞是我持续更新的动⼒~ 谢谢 Thanks♪( ω )
其他SQL学习笔记 友情链接:
JessieY:SQL学习笔记 - 窗⼝函数OVER z huanlan.zhihu
JessieY:SQL学习笔记 - CTE通⽤表表达式和WITH⽤法z huanlan.zhihu
JessieY:SQL学习笔记 - CASE WHEN THEN z huanlan.zhihu
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论