使用CASE和INNER JOIN进行MySQL查询错误

时间:2012-01-08 11:52:14

标签: mysql

我有一个名为'a'的用户信息表和一个包含来自不同API(twitter,foursquare)的数据的表,在此示例中,基于值 a.api_type应该成为b。我最终想要的是能够从活动API(api_foursquare或api_twitter)中获取正确的头像。

我一直试图让这个问题与此查询一起使用一段时间,但我一直收到此错误。 Sql不是我最强的观点,所以关于如何解决这个问题的任何提示都会很棒:)

  "[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

  INNER JOIN b ON b.user_id = a.user_id  at line 11"

SELECT a.user_id, 
       a.api_type, 
       b.avatar, 
       b.user_id
(CASE
       WHEN a.api_type = 0 THEN api_foursquare
       WHEN a.api_type = 1 THEN api_twitter
END) as b
FROM a WHERE a.cookie_hash = :cookie_hash
INNER JOIN b ON b.user_id = a.user_id

2 个答案:

答案 0 :(得分:5)

您无法选择要加入案例陈述的表格。您应该左键连接到两个表,然后在case语句中从其中一个表中选择值,如下所示:

SELECT a.user_id, 
       a.api_type,
       (case WHEN a.api_type = 0 THEN b.avatar ELSE c.avatar END) as avatar,
       (case WHEN a.api_type = 0 THEN b.user_id ELSE c.user_id END) as user_id
FROM a 
  LEFT OUTER JOIN api_foursquare b ON b.user_id = a.user_id
  LEFT OUTER JOIN api_twitter c ON c.user_id = a.user_id
WHERE a.cookie_hash = :cookie_hash

您可能不需要最后一个表达式(...as user_id),因为如果a.user_id或{{1}中有一行,它将等于api_twitter匹配api_foursquare

您还必须在a.user_id子句之后放置WHERE子句:

编辑:考虑到ypercube的好建议,查询将如下所示:

FROM

答案 1 :(得分:0)

您需要在b.user_id之后和(CASE之前使用逗号:

SELECT a.user_id, 
    a.api_type, 
    b.avatar, 
    b.user_id,
    (CASE
           WHEN a.api_type = 0 THEN api_foursquare
           WHEN a.api_type = 1 THEN api_twitter
    END) as b
FROM a WHERE a.cookie_hash = :cookie_hash
    INNER JOIN b ON b.user_id = a.user_id