0

Is it possible to do something like this:

SELECT 
  p.*, u.*
FROM
  posts AS p 
  IF(p.status = 1) 
  LEFT JOIN users AS u 
    ON u.id = p.user_id 
    ELSE 
  LEFT JOIN pusers AS u 
    ON u.id = p.user_id 
WHERE p.id = 10 ;

Based on post status being true/false join users/pusers table

1 Answer 1

3

No, but you can do this:

SELECT p.*,
       (case when p.status = 1 then u.col1 else pu.col1 end) as col1
FROM posts p LEFT JOIN
     users u 
     ON u.id = p.user_id and p.status = 1 LEFT JOIN
     pusers AS pu 
     ON pu.id = p.user_id and p.status <> 1
WHERE p.id = 10 ;

In other words, you can join both tables and use the values from the table, based on the condition.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, but I'm getting "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'u.col1' in 'field list' [code: 42S22]"
Sorry, my bad. I just needed a valid column name. It works perfect . Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.