dongluo3331 2011-06-15 02:15
浏览 42
已采纳

mysql命令由photo_id desc和shuffle之后

I want to select the most recent 12 rows from a table, but then shuffle the order.

So i cant use ORDER BY RAND() becouse that would just randomly pick some rows and not the most recent 12 rows.

I was thinking something like this, but it didnt work out as planned:

    $artig_photos = mysql_query("

    SELECT photo_id, photo_name
    FROM `migo_artig_photos`
    WHERE (
        photo_deleted=0 AND photo_type=2
    )
    ORDER BY photo_id DESC
    LIMIT 12;

");

while ($row = mysql_fetch_array($artig_photos)) {
    $artig_shuffled[$row['photo_id']] = $row['photo_name'];
}   

shuffle($artig_shuffled);

later when i do:

foreach ($artig_shuffled as $key => $value) {
}

i expected the key to be photo_id and the value to be photo_name with the correct relation between them, guess i was wrong.

Any tips about how to solve this problem? Maybe my approach isnt good at all.

Best of regards, Alexander

  • 写回答

3条回答 默认 最新

  • dongyan1808 2011-06-15 02:23
    关注

    You could use a subquery:

    SELECT * FROM (
      SELECT `migo_artig_photos`.`photo_id`,
             `migo_artig_photos`.`photo_name`
      FROM   `migo_artig_photos`
      WHERE  `migo_artig_photos`.`photo_deleted` = 0 AND
             `migo_artig_photos`.`photo_type` = 2
      ORDER BY photo_id DESC
      LIMIT 12) `top_12_migo_artig_photos`
    ORDER BY RAND();
    

    Alternatively, you could do this:

    // To shuffle:
    while ( $row = mysql_fetch_array($artig_photos) )
    {
      $artig_shuffled[] = $row;
    }
    
    shuffle($artig_shuffled);
    
    // To display:
    foreach ( $artig_shuffled as $row )
    {
      echo $row['photo_id'];
      echo $row['photo_name'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路