为什么这个IF THEN SQL语句会返回错误?

时间:2012-04-28 18:11:11

标签: mysql sql if-statement

我想在此SQL

中执行条件right join
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

有更好/正确的方法吗?

1 个答案:

答案 0 :(得分:2)

你的病情来自哪里?

  1. 如果它来自SQL之外,为什么不确定是否将连接放入该级别的查询中:

    $qry = "SELECT * FROM post " . ($test ? " RIGHT JOIN ... " : "") . "...";
    
  2. 否则,如果必须在SQL中进行测试,我会将不同的语句分开:

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