我有一个名为'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
答案 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