【问题标题】:#1054 - Unknown column 'countf' in 'where clause'#1054 - 'where 子句'中的未知列 'countf'
【发布时间】:2013-07-01 14:17:12
【问题描述】:

我不知道错误在哪里,请帮助我:)

SELECT a.*,b.*,users.*,
    (SELECT msg_text FROM message_private p 
     WHERE p.group_id=a.group_id ORDER BY occured_at DESC LIMIT 1) as message,
    (SELECT COUNT(f.profile_id) as countf from message_view f WHERE f.profile_id = 'sN07X2' AND f.id_group = b.group_id) 
FROM message_group a
JOIN message_group b ON a.group_id=b.group_id
INNER JOIN users ON users.profile_id = b.profile_id
WHERE a.profile_id = 'sN07X2'
AND b.profile_id != a.profile_id AND countf != 0 ORDER BY a.message_group_id DESC LIMIT 9

【问题讨论】:

  • 请提供错误信息...
  • @DanielRobertus 错误信息是标题..
  • 您不能在 WHERE 子句中使用 select 中的别名。
  • @Daanvn:没有。数字不需要单引号,只有字符文字(“字符串”)需要它们。
  • 您需要在计数之前进行分组,然后您可以添加一些条件,例如拥有COUNT(f.profile_id)<>0

标签: mysql


【解决方案1】:

问题是您试图从 WHERE 子句中的 SELECT 列表中引用列别名。您可能想查看使用 JOIN 与 message_view 表来获得结果,然后您可以过滤别名:

SELECT a.*,b.*,users.*,
    (SELECT msg_text 
    FROM message_private p 
    WHERE p.group_id=a.group_id 
    ORDER BY occured_at DESC LIMIT 1) as message,
    f.countf 
FROM message_group a
INNER JOIN message_group b ON a.group_id=b.group_id
INNER JOIN users ON users.profile_id = b.profile_id
LEFT JOIN 
(
    SELECT COUNT(profile_id) countf, id_group
    FROM message_view
    WHERE profile_id = 'sN07X2'
    GROUP BY id_group
) f
  on f.id_group = b.group_id
WHERE a.profile_id = 'sN07X2'
    AND b.profile_id != a.profile_id 
    AND countf != 0 
ORDER BY a.message_group_id DESC 
LIMIT 9

【讨论】:

  • 非常感谢,但出现此错误:#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 17 行的 'WHERE a.profile_id = 'sN07X2' AND b.profile_id != a.profile_id AND co' 附近使用正确的语法
【解决方案2】:

问题是您在子查询中定义countf 并且 试图在where 子句中引用它。相反,您需要在外部选择中有 as countf 并使用 having 子句:

SELECT a.*,b.*,users.*,
    (SELECT msg_text FROM message_private p 
     WHERE p.group_id=a.group_id ORDER BY occured_at DESC LIMIT 1) as message,
    (SELECT COUNT(f.profile_id) as countf from message_view f WHERE f.profile_id = 'sN07X2' AND f.id_group = b.group_id
   ) as countf
FROM message_group a
JOIN message_group b ON a.group_id=b.group_id
INNER JOIN users ON users.profile_id = b.profile_id
WHERE a.profile_id = 'sN07X2'
AND b.profile_id != a.profile_id
having countf <> 0
ORDER BY a.message_group_id DESC LIMIT 9

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多