Last x blog entries - but only once per user

前端 未结 4 1342
攒了一身酷
攒了一身酷 2020-12-18 13:59

I would like to display a box with the last x (say 5) blog entries. But I would like to avoid that a very active user is listed twice.

My tryout boils down to:

4条回答
  •  余生分开走
    2020-12-18 14:23

    how about if you try to use views for this one but it's a little bit weird solution something like:

    CREATE VIEW comm_blogs_publish_desc AS SELECT `User`.`id` AS `userid`, * 
    FROM `comm_blogs` AS `Blog` 
    LEFT JOIN `comm_users` AS `User` ON (`Blog`.`user_id` = `User`.`id`) 
    WHERE `Blog`.`status` = 1 
    ORDER BY `Blog`.`published` DESC;
    

    Then you could use it already to your original query:

    SELECT * 
    FROM comm_blogs_publish_desc
    GROUP BY `userid` LIMIT 5;
    

    It's just kind of weird because you still need to create the view but upon having it being grouped by userid you'll be sure that it's already sorted DESC by published date though because views are like virtual tables already, but it would be ideal if you specify which columns you'll really need because some of the column names may have conflict (same column names from other tables) if you'll just be using '*' to display all the columns on the table.

    I saw the new update you did on the query the issue appears because your using 2 columns on IN statement (it only accepts 1 column for the subquery and will return an error when you use 2 or more columns on it causing the cardinality issue) update it this way:

    SELECT `User`.`id`, `User`.`username`, `Blog`.`id`, `Blog`.`headline`, `Blog`.`published`, `UserInfo`.`gender`, `UserInfo`.`id` FROM `comm_blogs` AS `Blog` 
    LEFT JOIN `comm_users` AS `User` ON (`Blog`.`user_id` = `User`.`id`) 
    LEFT JOIN `comm_user_infos` AS `UserInfo` ON (`Blog`.`user_id` = `UserInfo`.`id`) 
    WHERE `User`.`active` = '1' AND `Blog`.`status` = 1 AND `Blog`.`id` IN (
        SELECT `LastBlog`.`id` 
        FROM comm_blogs AS LastBlog WHERE `LastBlog`.`status` = 1 
        GROUP BY `LastBlog`.`user_id` ORDER BY last DESC
    ) 
    ORDER BY `Blog`.`published` DESC LIMIT 0, 5;
    

    And then transfer the limit to the main query instead of the subquery to avoid the last issue: Syntax error or access violation: 1235 This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

    ;)

提交回复
热议问题