SELECT查询“大于”不能正常工作?

时间:2014-04-07 17:57:50

标签: php mysql

我在我的网站上编写了这个代码函数来显示用户消息:

function fetch_conversation_summery(){
    $sql = "SELECT
                `conversations`.`conversation_id`,
                `conversations`.`conversation_subject`,
                MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`
                MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`
            FROM `conversations`
            LEFT JOIN `conversations_messages` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
            INNER JOIN `conversations_members` ON `conversations`.`conversation_id` = `conversations_members`.`conversation_id`
            WHERE `conversations_members`.`userid` = {$_SESSION['userid']}
            AND `conversations_members`.`conversation_deleted` = 0
            GROUP BY `conversations`.`conversation_id`
            ORDER BY `conversation_last_reply` DESC";

    $result = mysql_query($sql);

    $conversations = array();

    while (($row = mysql_fetch_assoc($result)) !== false){
        $conversations[] = array(
            'id'               => $row['conversation_id'],
            'subject'          => $row['conversation_subject'],
            'last_reply'       => $row['conversation_last_reply'],  
            'unread_messages'  => ($row['conversation_unread'] == 1),
        );
    }

    return $conversations;
}

虽然当我尝试在正确的页面上使用它时,它会发出错误:

mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in...

我将问题放在查询中,在行中:

MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`

虽然似乎没有什么我可以看到它的错误,但所有的表名都是正确的,但它仍然是错误的?有没有人有任何想法可能导致这个?

P.S代码工作正常,没有MAX线,我提到错误的位置。

2 个答案:

答案 0 :(得分:1)

此行之后您缺少逗号:

MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`

应该是:

MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`,

答案 1 :(得分:0)

尝试替换此

   MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`

通过

  CASE WHEN MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` THEN max(`conversations_messages`.`message_date`) END AS `conversation_unread`