#1054 - 未知栏' countf'在' where子句'

时间:2013-07-01 14:17:13

标签: mysql

我不知道哪里有错误请帮帮我:)。

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

2 个答案:

答案 0 :(得分:0)

问题是您正在尝试从WHERE子句中的SELECT列表引用列别名。您可能希望使用带有message_view表的JOIN来获取结果,然后可以对别名进行过滤:

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

答案 1 :(得分:0)

问题是您在子查询中定义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