mysql子查询/联合查询

一、where 或having后面

      1、标量子查询(单行子查询)

      2、列子查询(多行子查询)

      3、行子查询(多列多行)

   特点:

        子查询放在小括号内

        子查询一般放在条件右侧

        标量子查询,一般搭配着单行操作符使用  in、any/some、all

       例:       

#where后使用子查询
select * from 表名1 where 字段>(
    select money from 表名2 where name='小鸣'
);

select * from 表名1 where 字段>(
    select money from 表名2 where name='小鸣'
) and id = (
    select id from 表名3 where id = 1
);
#having后面使用子查询
select * from 表名1 where 字段 = (
    select id from 表名2 where name = '小鸣' group by groupId
) having money >(
    select money from 表名3 where name='小鸣'
)

     执行顺序:先把子查询执行完得到结果主程序再使用这个结果去查询

     2 列子查询

          返回多行

          使用多行比较操作符

                     in/not in           等于列表中的任意一个        *

                     any|some        和子查询返回的某一个值比较   (使用少)

                     all                    和子查询返回的所有值比较

#子查询是多行单列的结果
select name from ***1 where 关联id in (
    select id from ***2 where uid in (**,**,**,....)
);

#any 满足子查询中的任何一个条件

            行子查询:结果集一行多列或多行多列

二、select 后面的子查询

select d.*,(
    select count(*) from ***1 e where e.uid = d.uid
) num  from ***2 d

三、from后面的子查询

       

四、exists后面使用子查询(相关子查询)        

就是查看子查询中是否有值

一般用exisits的查询都可以使用 in 之类的代替

五、联合查询

     关键字:union     联合、合并

     语法:查询语句1 union 查询语句2 union.......

             将多条查询语句的结果合并成一个结果

            

           注意:

                 关联的查询语句查询的列数必须一样

                 关联查询的字段每一列的字段和顺序最好一致

                 使用union关键字默认去重,使用union all 包含重复项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值