pepe
pepe

Reputation: 9909

Why does this IF THEN SQL statement return an error?

I want to perform a conditional right join in this SQL

SELECT *
 FROM   post
   IF   1 = 1 THEN RIGHT JOIN faves ON faves.post_id_fk = post_id;  // <== error
END IF;
 WHERE  post_author_id
        LIKE 1
 ORDER  BY post_timestamp DESC
 LIMIT  0, 10

Is there a better/right way of doing this?

Upvotes: 0

Views: 119

Answers (1)

eggyal
eggyal

Reputation: 125865

From where does your condition originate?

  1. If it comes from outside of SQL, why not determine whether or not to put the join into your query at that level:

    $qry = "SELECT * FROM post " . ($test ? " RIGHT JOIN ... " : "") . "...";
    
  2. Otherwise, if it must be tested within SQL, I'd separate the different statements apart:

    DELIMITER ;;
    
    IF @test THEN
        SELECT * FROM post RIGHT JOIN ... ;
    ELSE
        SELECT * FROM post ... ;
    END IF;;
    
    DELIMITER ;
    

Upvotes: 2

Related Questions