【问题标题】:Why does Mysql keep telling me there is an unknown column even though I've declared the alias?为什么即使我已经声明了别名,Mysql 仍然告诉我有一个未知列?
【发布时间】:2021-06-21 03:07:48
【问题描述】:

我在这里有这个 mySQL 查询,它应该给我一个用户的所有朋友的计数。但是,我需要进一步过滤以仅包含由“status = 20”指定的已确认好友请求。 当我尝试在 WHERE 子句中执行此操作时,我不断收到以下错误

错误代码:1054。“字段列表”中的“f.status”列未知。

我的查询在这里:

Select
  u.uuid, u.nick,
  count(distinct f.friend_uuid) as number_of_friends, f.status
From
  user u
    Left Outer Join (
      Select user_uuid, friend_uuid from user_friend 
      Union All
      Select friend_uuid, user_uuid from user_friend 
  )  as f
    On u.uuid = f.user_uuid
    WHERE f.status = '20'
 GROUP BY 1,2,4
    HAVING number_of_friends >=10;

【问题讨论】:

  • 您能否格式化您的代码并将其放入代码块中?这种文本格式很难阅读!
  • 您的 f 子查询返回两列:user_uuid 和friend_uuid。您的意思是在子查询中选择状态?

标签: mysql


【解决方案1】:

您的查询有 3 个问题。

  1. 您可以通过这种方式使用别名。别名将在创建结果集后创建。结果集将使用 HAVING 子句。因此,having 子句必须在结果集中具有名称。这在下面的查询中得到纠正。

  2. 您使用了 WHERE f.status = '20'。 f 用作左外连接。如果您在 where 子句中使用 ouer 连接列,则它将成为内部连接。这在下面的查询中得到更正。

  3. 左外连接的内查询在选择中没有状态列。因此它会抛出错误。

    选择 u.uuid, u.nick, count(distinct f.friend_uuid) as number_of_friends, f.status 来自用户 u 左外连接 ( 从 user_friend 中选择 user_uuid、friend_uuid、[STATUS_COLUMN REQUIRED] 联合所有 从 user_friend 中选择friend_uuid、user_uuid、[STATUS_COLUMN REQUIRED] ) as f On u.uuid = f.user_uuid and f.status = '20' 按 1、2、4 分组 HAVING count(distinct f.friend_uuid) >=10;

如果您仍然遇到任何问题,请告诉我。

【讨论】:

  • 嗨,阿米特,发布此消息后 - 我意识到自己的错误,并以与您相同的方式重新创建了查询。但无论如何,感谢您的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2021-04-23
相关资源
最近更新 更多