在mysql语句中使用'as'时出现未知列错误

时间:2013-08-10 04:24:57

标签: mysql select

我有这个MySQL声明:

SELECT a.id, a.`from member_id`, a.`to member_id`, IF(a.`from member_id`=1, a.`to member_id`, a.`from member_id`) as other_id, a.text, MAX(a.`date sent`) as `date sent`
FROM message a
JOIN members m on other_id=m.id
WHERE (a.`from member_id`=1 OR a.`to member_id`=1) AND a.active=1
GROUP BY other_id
ORDER BY other_id DESC, `date sent` DESC

但我收到了错误:

#1054 - Unknown column 'other_id' in 'on clause' 

我正在使用as键创建该列。有谁知道这里有什么不对吗?

感谢。

1 个答案:

答案 0 :(得分:2)

as会创建列别名(在本例中为other_id),您无法加入列别名。您可以在ORDER BY中使用别名,但不能使用别名,除非别名来自子查询。

这里你最好的选择是在连接中重复IF函数:

SELECT
  a.id,
  a.from member_id,
  a.to member_id,
  IF(a.from member_id=1, a.to member_id, a.from member_id) as other_id,
  a.text,
  MAX(a.date sent) as date sent
FROM message a
JOIN members m on IF(a.from member_id=1, a.to member_id, a.from member_id) = m.id
WHERE (a.from member_id=1 OR a.to member_id=1) AND a.active=1
GROUP BY other_id
ORDER BY other_id DESC, date sent DESC