具有左连接条件的MySQL case语句

时间:2016-04-08 22:53:22

标签: mysql case case-when

我在下面有一个MySQL请求,但它无法正常工作。

错误:

  

#1054 - 未知专栏' uid'在' on条款'

查询:

SELECT 
  u.email,
  CASE 
  WHEN c.from_user_id = '301' THEN c.to_user_id 
  WHEN c.to_user_id = '301' THEN c.from_user_id 
  END AS uid
FROM `contacts` AS c
LEFT JOIN `users` AS u 
ON u.id = uid
HAVING uid >0

如何撰写正确的请求?

1 个答案:

答案 0 :(得分:1)

您不能在同一WHERE的{​​{1}}子句中引用列别名,因为SELECT用于在WHERE子句运行之前查找行在他们。把它放到子查询中。

SELECT