1

我有这个 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密钥创建该列。有谁知道这里有什么问题?

谢谢。

4

1 回答 1

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
于 2013-08-10T04:42:46.313 回答