WHERE vs HAVING

后端 未结 7 2044
北荒
北荒 2020-11-22 08:20

Why do you need to place columns you create yourself (for example select 1 as \"number\") after HAVING and not WHERE in MySQL?

相关标签:
7条回答
  • 2020-11-22 08:49

    These 2 will be feel same as first as both are used to say about a condition to filter data. Though we can use ‘having’ in place of ‘where’ in any case, there are instances when we can’t use ‘where’ instead of ‘having’. This is because in a select query, ‘where’ filters data before ‘select’ while ‘having’ filter data after ‘select’. So, when we use alias names that are not actually in the database, ‘where’ can’t identify them but ‘having’ can.

    Ex: let the table Student contain student_id,name, birthday,address.Assume birthday is of type date.

    SELECT * FROM Student WHERE YEAR(birthday)>1993; /*this will work as birthday is in database.if we use having in place of where too this will work*/
    
    SELECT student_id,(YEAR(CurDate())-YEAR(birthday)) AS Age FROM Student HAVING Age>20; 
    /*this will not work if we use ‘where’ here, ‘where’ don’t know about age as age is defined in select part.*/
    
    0 讨论(0)
提交回复
热议问题