Correct understanding of the difference between where and having in MySQL (reproduced)

Source: Internet
Author: User

Here is an example of a specific explanation:

1. Where and having a scene that can be used
    select goods_price,goods_name from sw_goods where goods_price > 100
        select goods_price,goods_name from sw_goods having goods_price > 100

Explanation: The above has the premise that I have filtered out the Goods_price field, in this case and where the effect is equivalent, but if I did not select Goods_price will be an error!! Because having is a filtered field from the previous filter, where is filtered directly from a field in the data table.

2. Can only use where, can not use the situation of having
    select goods_name,goods_number from sw_goods where goods_price > 100
    select goods_name,goods_number from sw_goods having goods_price > 100 //报错!!!因为前面并没有筛选出goods_price 字段

3. Can only be used having, can not use where condition

Inquire about the average price of each goods_category_id commodity and get an average price greater than $1000

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

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

Note: The field behind the where is the data table, if I change the AG to AVG (Goods_price) is also wrong! Because the field is not in the table. And having just according to the previous query out of what can be followed by what.

Correct understanding of the difference between where and having in MySQL (reproduced)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.