SQL多表查询

1.sql的四种基本操作:增删改查

  • 插入语句insert

insert into <表名> values(列值);
insert into <表名>(列名A,列名B) values(列值);
  • 删除语句 delete

    delete from <表名> where 删除条件;

  • 修改语句 update

update <表名> set [列名=更新值] where 更新条件;
  • 查询语句 select

    select from <表名>;   #查询所有字段
    select 字段名 from 表名; #查询指定字段
    distinct
    select distinct 字段名 from表名;  #查询指定字段输出唯一不同的值
    select from <表名> where 条件;   #查询指定某条数据
    select from <表名> where 条件1 or 条件2;   #or可以查询多个条件的数据;
    limit:
    select from 表名 limit 20;   #查询表中前20条数据
    select from 表名 limit 5,20;   #查询表中第5到20条数据
    like
    select from 表名 where 字段 like "n%";  #查询指定表名中某个字段以n开头的数据
    select from 表名 where 字段 like "%n";  #查询指定表名中某个字段以n结尾的数据
    select from 表名 where 字段 like "%n%";  #查询指定表名中某个字段包含n的数据
    select from 表名 where 字段 not like "%n%";  #查询指定表名中某个字段不包含n的数据
    order byorder by 字段名 asc(升序)/desc(降序)
    select from 表名 order by 字段名 desc limit n; 倒序查看前n行

2.sql内置函数:对select结果做操作

count #适用任何数据类型
sum  #适用数字类数据类型
avg  #适用数字类数据类型
max  #适用数值、字符串、日期时间数据类型
min  #适用数值、字符串、日期时间数据类型
select max(字段名) from 表名;
AS 关键字可以给值重命名:select max(字段名) as new_name from 表名;

 

3.子查询

1.单行单列子查询
select from job_runtime q where q.upload_time=(select min(upload_time) from job_runtime);
#查询job_runtime表中upload_time最小的作业完整时间
 
select from user where q.update_time > (select update_time from user where user_id = 1207960959851704320);
#查询user表中更新时间‘update_time’大于user_id为1207960959851704320的更新时间的全部user信息
 
2.单行多列子查询
select from user where q.update_time > (select update_time from user where user_id = 1207960959851704320)
and q.create_time>(select create_time from user where account_id =1207973353072099328);
#查询user表中更新时间‘update_time’大于user_id为1207960959851704320的更新时间
#且 创建时间大于account_id =1207973353072099328的创建时间的全部user信息
 
3.多行单列子查询(INANYALL)

4.连接查询

1.内连接:有效的去除笛卡尔集现象
    1.1隐式内连接
        select from A 别名1,B 别名2 where 别名1.xx=别名2.xx
        #select from job j,job_runtime jr where j.id = jr.job_id;
        #select count(j.project_id) from job j,job_runtime jr where j.id = jr.job_id and j.project_id=1242321444738707456;
    1.2显式内连接
        select from A 别名1 inner join B 别名2 on 别名1.xx=别名2.xx
 
2.外连接:包括左外连接和右外连接
    2.1左外连接:左边的表的内容全部显示,然后匹配右边的表,如果右边的表匹配不到,则空
        select from left outer join on 条件
    2.2右外连接:右边的表的内容全部显示,然后匹配左边的表,如果左边的表匹配不到,则空
        select from right out join on 条件

5.分组查询

窗口函数:可以对数据库数据进行实时分析处理。
窗口函数基本语法:<窗口函数> over(partition by <用于分组的列名> order by <用于排序的列名>)
<窗口函数>可放以下两种函数:
a.专用窗口函数:rank、dense、row_number等
b.聚合函数:sum、avg、count、max、min等
窗口函数作用:处理组内排序问题;不减少原表的行数。

 

posted @ 2021-04-09 15:53  迪斯尼的狮子王  阅读(138)  评论(0)    收藏  举报