zoukankan      html  css  js  c++  java
  • MySQL中where和on,where和having 的区别

    where和on的区别

      
      用到连接查询时on会常用到,我们以左连接为例,来了解on的作用。

      on是在生成临时表使用的条件,不管on子句的条件是否为真,其都会返回左表的数据,如果条件为真则右表对应的数据也将会显示,如果为假则只返回左表的数据对应的有表的数据为null。

      实例演示:

    创建数据表

    create table fruits(
    f_id int(11) primary key auto_increment,
    f_name varchar(50) not null,
    f_price float not null
    
    );
    
    create table customers(
    c_id int(11) primary key auto_increment,
    fruits_id int(11) not null,
    foreign key(fruits_id) references fruits(f_id)
    );
    #插入数据
    insert into fruits(f_id,f_name,f_price) values
    (1,'apple',10),
    (2,'banalan',5),
    (3,'anrange',6);
    insert into customers(c_id,fruits_id)values
    (1,2),
    (2,2),
    (3,1);

    on单条件查询

       select c_id ,f_price
    from 
        customers left outer join fruits
    on
        customers.fruits_id = fruits.f_id;

     on多条件查询

        select c_id ,f_price
    from 
        customers left outer join fruits
    on
        customers.fruits_id = fruits.f_id and fruits.f_id = 1;

    从两个结果中可以看出查询结果的总数并没有发生变化,实际上on的子句的作用是筛选连接表(fruits)要显示的内容,并不影响查询结果的条数。

    在on后加上where语句

       select c_id ,f_price
    from 
        customers left outer join fruits
    on
        customers.fruits_id = fruits.f_id where fruits.f_id = 1;

     查询结果变为一条ON后的WHERE子句的实际作用是 对多表连接的结果进行筛选,满足条件的记录才能被留下,所以他会影响 最终的查询记录数

    where和having的区别

    原文链接:https://blog.csdn.net/yexudengzhidao/article/details/54924471

    1. where和having都可以使用的场景

        select goods_price,goods_name from sw_goods where goods_price > 100

        1

            select goods_price,goods_name from sw_goods having goods_price > 100

        1

    解释:上面的having可以用的前提是我已经筛选出了goods_price字段,在这种情况下和where的效果是等效的,但是如果我没有select goods_price 就会报错!!因为having是从前筛选的字段再筛选,而where是从数据表中的字段直接进行的筛选的。
    2. 只可以用where,不可以用having的情况

        select goods_name,goods_number from sw_goods where goods_price > 100

        1

        select goods_name,goods_number from sw_goods having goods_price > 100 //报错!!!因为前面并没有筛选出goods_price 字段

        1

    3. 只可以用having,不可以用where情况

    查询每种goods_category_id商品的价格平均值,获取平均价格大于1000元的商品信息

        select goods_category_id , avg(goods_price) as ag from sw_goods group by goods_category having ag > 1000

        1

        select goods_category_id , avg(goods_price) as ag from sw_goods where ag>1000 group by goods_category //报错!!因为from sw_goods 这张数据表里面没有ag这个字段

        1

    注意:where 后面要跟的是数据表里的字段,如果我把ag换成avg(goods_price)也是错误的!因为表里没有该字段。而having只是根据前面查询出来的是什么就可以后面接什么。

    笨鸟先飞
  • 相关阅读:
    js最佳实践
    js图片库 案例
    DOM
    js语法
    导航栏的ul中的li设置问题
    wDatepicker97的用法(点击事件联动)
    jqueyr validtion的使用
    哥哥写的例子(后台没有进行排序分组的时候,前台进行自己分组)
    关于require js加载的时候报错的问题
    一些简单的三目运算的使用(举例购物车)
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/14516377.html
Copyright © 2011-2022 走看看