PHP和MySQL,这个函数有什么问题?

时间:2012-04-17 18:22:12

标签: php mysql

此功能不起作用,我找不到问题,这是查询中的某个地方。

function get_category_posts($category, $page, $per_page) {
$start = (int)($page - 1) * $per_page;
$per_page = (int)$per_page;

$sql = "SELECT
    `posts`.`post_id` AS `id`,
    `posts`.`post_title` AS `title`,
    `posts`.`post_category` AS `category`,
    `posts`.`post_body` AS `preview`,
    `posts`.`post_user` AS `user`,
    DATE_FORMAT(`posts`.`post_date`, '%Y-%m-%d %H:%i:%s') AS `date`,
    `comments`.`total_comments`,
    DATE_FORMAT(`comments`.`last_comment`, '%Y-%m-%d %H:%i:%s') AS `last_comment`
FROM `posts`
WHERE `category`='".$category."'
LEFT JOIN (
    SELECT
        `post_id`,
        COUNT(`comment_id`) AS `total_comments`,
        MAX(`comment_date`) AS `last_comment`
    FROM `comments`
    GROUP BY `post_id`
) AS `comments`
ON `posts`.`post_id` = `comments`.`post_id`
ORDER BY `posts`.`post_date` DESC
LIMIT {$start}, {$per_page}";

$posts = mysql_query($sql);
//die(mysql_error());

$rows = array();
while (($row = mysql_fetch_assoc($posts)) !== false) {
    $rows[] = array(
        'id' => $row['id'],
        'title' => html_entity_decode($row['title']),
        'category' => html_entity_decode($row['category']),
        'preview' => html_entity_decode($row['preview']),
        'user' => html_entity_decode($row['user']),
        'date' => $row['date'],
        'total_comments' => ($row['total_comments'] === null) ? 0 : $row['total_comments'],
        'last_comment' => ($row['last_comment'] === null) ? 'aldrig' : $row['last_comment']
        );
}

return $rows;

} 该函数在没有WHERE类别='".$category."'的情况下工作正常,但是,使用它返回

  

您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在第12行“LEFT JOIN(SELECT post_id,COUNT(comment_id)AS total_comments”附近使用正确的语法

2 个答案:

答案 0 :(得分:5)

WHERE子句必须在表连接之后和ORDER BY和LIMIT

之前
SELECT <column list>
FROM <table>
JOIN <table> USING (<column>)
WHERE <condition>
OR <condition>
AND <condition>
GROUP BY <column list>
HAVING <expression>

答案 1 :(得分:2)

JOIN必须在WHERE条件

之前
$sql = "SELECT
    `posts`.`post_id` AS `id`,
    `posts`.`post_title` AS `title`,
    `posts`.`post_category` AS `category`,
    `posts`.`post_body` AS `preview`,
    `posts`.`post_user` AS `user`,
    DATE_FORMAT(`posts`.`post_date`, '%Y-%m-%d %H:%i:%s') AS `date`,
    `comments`.`total_comments`,
    DATE_FORMAT(`comments`.`last_comment`, '%Y-%m-%d %H:%i:%s') AS `last_comment`
FROM `posts`
LEFT JOIN (
    SELECT
        `post_id`,
        COUNT(`comment_id`) AS `total_comments`,
        MAX(`comment_date`) AS `last_comment`
    FROM `comments`
    GROUP BY `post_id`
) AS `comments`
ON `posts`.`post_id` = `comments`.`post_id`
WHERE `posts`.`category`='".$category."'
ORDER BY `posts`.`post_date` DESC
LIMIT {$start}, {$per_page}";