LEFT JOIN和ORDER BY中的Mysql GROUP BY

时间:2013-07-30 16:09:56

标签: mysql group-by sql-order-by left-join

我有这个查询工作正常

    $query = "SELECT 
        beva_post.*, 
        CONVERT_TZ(beva_post.date_published, '-00:00', '+00:00') as moment, 
        beva_rubrique.titre_en, 
        beva_user.image_user   
        FROM beva_post 
        LEFT JOIN beva_user 
            ON beva_user.id_user = beva_post.id_user 
        LEFT JOIN beva_rubrique 
            ON beva_rubrique.id_rubrique = beva_post.id_rubrique 
        LEFT JOIN beva_post_like 
            ON beva_post_like.id_post = beva_post.id_post 
        WHERE beva_post.id_user != '' 
        AND beva_post.flag = 'true' ";
$query .= "ORDER BY beva_post.id_post DESC ";
$query .= "LIMIT 50";

但我想订阅这个查询不是通过id_post DESC而是通过id_post在表中最像id_user(DESC)beva_post_like

beva_post_like表如下所示:

    +-------------+--------------+
    | id_post     | id_user      |
    +-------------+--------------+
    | 1           | 20           |
    | 1           | 11           |
    | 1           | 10           |
    | 2           | 20           |
    | 2           | 50           |
    | 1           | 15           |
    +-------------+--------------+

我在LEFT JOIN beva_post_like中尝试使用GROUP BY,但它不起作用!

我是否必须使用更多查询?

感谢您的帮助......

克里斯

在你的答案之后我做了这个,但我仍然在最后有一些'喜欢'的帖子

    $query = "SELECT 
        beva_post.*, 
        COUNT(beva_post.id_post) as cpt, 
        CONVERT_TZ(beva_post.date_published, '-00:00', '+00:00') as moment, 
        beva_rubrique.titre_en, 
        beva_user.image_user  
        FROM beva_post 
        LEFT JOIN beva_user 
            ON beva_user.id_user = beva_post.id_user 
        LEFT JOIN beva_rubrique 
            ON beva_rubrique.id_rubrique = beva_post.id_rubrique 
        LEFT JOIN beva_post_like 
            ON beva_post_like.id_post = beva_post.id_post 
        WHERE beva_post.id_user != '' 
        AND beva_post.flag = 'true' ";
$query .= "GROUP BY beva_post.id_post ";
$query .= "ORDER BY cpt DESC ";
$query .= "LIMIT 50";

1 个答案:

答案 0 :(得分:1)

您希望按喜欢它的用户数排序帖子吗? 如果是这种情况,您可以GROUP BY id_post在此COUNT(id_user)上的SELECT和ORDER BY DESC中添加COUNT(id_user)

如果我误解了你的问题,你能更准确地了解你的ORDER BY目标吗?