在PHP查询中添加顺序

时间:2014-07-23 17:56:46

标签: php sql

我曾尝试向此添加DESCASC,但我仍然无法正确订购。只是想确保我在正确的位置上尝试。

$query = $db->query("
        SELECT n.*, COUNT(c.id) as replies, u.username, u.displaygroup, u.usergroup, u.avatar
        FROM " . TABLE_PREFIX . "news n
        LEFT JOIN " . TABLE_PREFIX . "newscomments c ON (c.nid = n.id)
        LEFT JOIN " . TABLE_PREFIX . "users u ON (u.uid = n.uid)
        WHERE FIND_IN_SET($cid, n.cid)
        GROUP BY n.id
        ORDER BY n.date_posted
        LIMIT $start, $perpage
    ");

我试过了

ORDER BY n.date_posted DESC

ORDER BY n.date_posted ASC

这是放这个的正确位置吗?我想把最新消息放在首位。

1 个答案:

答案 0 :(得分:0)

尝试将回复重构为子查询:

$query = $db->query("                                                          
    SELECT 
      n.*,                                                                
      (SELECT COUNT(c.id) FROM " . TABLE_PREFIX . "newscomments c WHERE c.id = n.id) as replies,
       u.username, u.displaygroup, u.usergroup, u.avatar                       
    FROM " . TABLE_PREFIX . "news n                                            
    LEFT JOIN " . TABLE_PREFIX . "users u ON (u.uid = n.uid)                   
    WHERE FIND_IN_SET($cid, n.cid)                                             
    ORDER BY n.date_posted                                                     
    LIMIT $start, $perpage                                                     
");