如何修复MySQL查询别名未知列? 2018年 [英] How to fix MySQL Query Alias unknown column? 2018

查看:98
本文介绍了如何修复MySQL查询别名未知列? 2018年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器版本:5.6.38-MySQL社区服务器(GPL)
PHP版本:7.2.1
PHPMyAdmin:版本信息:4.7.7

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

这是我的mysql查询

This is my mysql query

SELECT r.id, r.url, MAX(date) as `max_date`, date
FROM report as r
WHERE max_date = date
GROUP BY id, url
ORDER BY bid DESC;

我想检索maxdate的结果.

I wanted to retrieve the result of maxdate.

我已经尝试过HavingBetween,但是它不起作用.别名是未知列"

I have already tried Having and Between it just doesn't work. The alias is unknown column

我想做的是

我想获取网址的最新日期.

I want to retrieve the most recent date of a url.

示例:
ID,网址,日期
1,facebook.com,2018年1月1日
2,google.com,2018年1月2日
3,facebook.com,2018年1月5日
4,youtube.com,2018年1月6日
5,youtube.com,2018年1月1日
6,stackoverflow.com,2018年1月7日
7,stackoverflow.com,2018年1月8日

Example:
id, url, date
1, facebook.com, jan 1, 2018
2, google.com, jan 2, 2018
3, facebook.com, jan 5, 2018
4, youtube.com, jan 6, 2018
5, youtube.com, jan 1, 2018
6, stackoverflow.com, jan 7, 2018
7, stackoverflow.com, jan 8, 2018

通过运行应检索的查询,
2018年1月3日,facebook.com
2,google.com,2018年1月2日
4,youtube.com,2018年1月6日
2018年1月7日,stackoverflow.com,

By running the query it should retrieve,
3, facebook.com, jan 5, 2018
2, google.com, jan 2, 2018
4, youtube.com, jan 6, 2018
7, stackoverflow.com, jan 8, 2018

推荐答案

根据 MySQL 5.7参考手册

标准SQL不允许在WHERE中引用列别名 条款

Standard SQL disallows references to column aliases in a WHERE clause

您不应在WHERE子句中使用别名,因为别名是在运行查询时生成的,并且在执行WHERE条件时可能未准备好.您将获得别名未知列错误,因为MySQL在查询结果生成后才知道别名.因此,您不能在此处的WHERE子句中使用别名.

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.

(问题编辑后添加)

您可以通过以下查询获得所需的结果:

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;

查询说明:在SELECT子句中,您仅提及要显示的列,MAX()函数本身已经选择了最大值(因此您不需要WHERE子句),而GROUP BY子句告诉您结果,然后根据idurl对所有结果进行分组.

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.

这篇关于如何修复MySQL查询别名未知列? 2018年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆