1
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 ***;

I want to join different table according to blogid, when blogid is 0, join user_dp, else join user_blog.But it returns 1064 error. How to solve this problem?

Specs
  • 103
  • 1
  • 7

3 Answers3

0

You can do this with left join and filter the right result by 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
***;

For more info refer : MySQL query where JOIN depends on CASE

If you are trying to inner join to filter data on condition then;

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 ****;
Community
  • 1
  • 1
Praveen
  • 8,945
  • 4
  • 31
  • 49
0

USE:

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 ***;

Replace users, user_role and product_category with your tables.

Ankur Mahajan
  • 3,396
  • 3
  • 31
  • 42
0

The other answers posted here are the correct solutions. I'll answer the "Why do I get 1064" for you.

The syntax you've written is invalid. You cannot "conditionally" join to a table like this.

What you can do is LEFT JOIN - which as opposed to [INNER] JOIN means "return NULL for all fields on this table if no record matches the join condition".

There's lots on the Internet about LEFT vs INNER joins, and MySQL's website documents the COALESCE function very well.

Have a play and a read, you'll figure it out why the other solutions work.


Upon reflection, I felt this could benefit from some additional explanation.

See this SQLFiddle: http://sqlfiddle.com/#!9/043b7/6

wally
  • 3,492
  • 25
  • 31