How to fix MySQL Query Alias unknown column? 2018

后端 未结 1 1292
死守一世寂寞
死守一世寂寞 2021-01-28 00:26

Server version: 5.6.38 - MySQL Community Server (GPL)
PHP version: 7.2.1
PHPMyAdmin: Version information: 4.7.7

This is my mysql query

SELECT r         


        
1条回答
  •  -上瘾入骨i
    2021-01-28 00:46

    According to MySQL 5.7 Reference Manual,

    Standard SQL disallows references to column aliases in a WHERE clause

    You should not use an alias in WHERE clause since the alias is generated upon running the query and may not be ready when the WHERE condition executes. You get alias is unknown column error because MySQL is not aware of the alias until after it is generated as result of the query. Therefore you can not use alias in WHERE clause here.

    (Addition after question edit)

    You can get desired result with following query:

    SELECT r.id, r.url, MAX(date) as `max_date`
    FROM report as r
    GROUP BY id, url;
    

    Query Explanation: In SELECT clause you only mention the columns you want to display, the MAX() function will already select the maximum values itself (so you do not need a WHERE clause), and the GROUP BY clause tells the result to group all results based on id and then url.

    0 讨论(0)
提交回复
热议问题