三元if语句用于mysql查询

时间:2014-05-12 20:00:01

标签: php mysql if-statement ternary-operator

如何为$ sql变量添加更多三元if语句?当我尝试添加更多时,它输出空白:

工作:

$sql = "SELECT r.title,r.author,r.summary,r.posted_on,r.review_url,r.rating 
        FROM reviews r 
        LEFT JOIN websites w 
        ON w.id=r.website_id 
        WHERE w.rooftop_id=$rooftop_id
        AND review_site_id IN ($sites)
        AND rating >= $star_threshold
        AND review_status_id=2
        " . ($pagination == 1 ? " LIMIT $offset, $review_limit " : "");

不工作:

$sql = "SELECT r.title,r.author,r.summary,r.posted_on,r.review_url,r.rating 
        FROM reviews r 
        LEFT JOIN websites w 
        ON w.id=r.website_id 
        WHERE w.rooftop_id=$rooftop_id
        AND review_site_id IN ($sites)
        AND rating >= $star_threshold
        AND review_status_id=2
        " . ($pagination == 1 ? " LIMIT $offset, $review_limit " : "")
        " . ($rating_filter == 1 ? " ORDER BY r.rating " : "");

2 个答案:

答案 0 :(得分:2)

您的查询中有拼写错误,请尝试以下操作:

$sql = "SELECT r.title,r.author,r.summary,r.posted_on,r.review_url,r.rating 
        FROM reviews r 
        LEFT JOIN websites w 
        ON w.id=r.website_id 
        WHERE w.rooftop_id=$rooftop_id
        AND review_site_id IN ($sites)
        AND rating >= $star_threshold
        AND review_status_id=2
        " . ($pagination == 1 ? " LIMIT $offset, $review_limit " : "")
        . ($rating_filter == 1 ? " ORDER BY r.rating " : "");

答案 1 :(得分:1)

就MySQL而言,LIMIT子句不能位于ORDER BY语句中的SELECT子句之前。 ORDER BY子句必须在之前 LIMIT子句。


你在php语法中遇到了一个简单的问题,在你发布的最后一行代码的开头有一个额外的双引号。