简体   繁体   中英

Mysql GROUP BY in LEFT JOIN and ORDER BY

I have this query which works fine

    $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";

But I would like to ORDER this query not by id_post DESC but by id_post that have the most like by id_user (DESC) in the table beva_post_like

The beva_post_like table looks like this :

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

I tried with GROUP BY in the LEFT JOIN beva_post_like but it does not work !

Do I have to use more queries ?

Thanks for your help...

Chris

After your answer I did this but I still have some posts with 'like' at the end

    $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";

You want to have posts ordered by count of users that liked it? If it is that case, you can GROUP BY id_post , adding a COUNT(id_user) in the SELECT and ORDER BY DESC on this COUNT(id_user) .

If I misunderstand your question, can you be more precise on your ORDER BY goal?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM