关于 Mysql 错误时加入 case

About Mysql join case when error

select t.* FROM user_tq t join 
CASE when t.blogid = 0 then user_dp ELSE  user_blog END b
on t.uid = b.uid where ***;

我想根据blogid加入不同的table,当blogid为0时加入user_dp,否则加入user_blog.But就returns1064错误. 如何解决这个问题?

您可以使用 left join 执行此操作并通过 COALESCE

过滤正确的结果
select t.* 
FROM user_tq t 
left join user_dp ud on t.blogid = 0 and t.uid = ud.uid
left join user_blog ub on t.blogid != 0 and t.uid = ub.uid
where
COALESCE(ud.uid, ub.uid) IS NOT NULL and
***;

更多信息请参考:MySQL query where JOIN depends on CASE

如果您正在尝试 inner join to filter 条件数据,那么;

select * from (
    select t.* 
    FROM user_tq t 
    join user_dp ud on t.blogid = 0 and t.uid = ud.uid
    union all
    select t.* 
    FROM user_tq t 
    join user_blog ub on t.blogid != 0 and t.uid = ub.uid
) as x
where ****;

使用:

select * FROM users t
left join user_role r ON t.user_id = 0 AND r.user_id = t.user_id
left join product_category c ON t.user_id != 0 AND c.user_id = t.user_id
WHERE COALESCE(r.user_id, c.user_id) IS NOT NULL
WHERE ***;

用您的表替换用户 user_role 和 product_category。

此处发布的其他答案是正确的解决方案。 我会为你回答"Why do I get 1064"。

您所写的语法无效。你不能像这样 "conditionally" 加入 table。

可以 做的是 LEFT JOIN - 与 [INNER] JOIN 相对的意思是 "return NULL for all fields on this table if no record matches the join condition".

Internet 上有很多关于 LEFTINNER 联接的内容,MySQL 的网站很好地记录了 COALESCE 函数。

边玩边读,您就会明白为什么其他解决方案有效。


经过深思熟虑,我觉得这可能需要一些额外的解释。

查看此 SQLFiddle:http://sqlfiddle.com/#!9/043b7/6