douka19950505 2014-05-13 19:59
浏览 43
已采纳

在WordPress中查询自定义表以首先返回最近的行

I have created a custom table which stores 'post likes' in WordPress.

$sql[] = "CREATE TABLE IF NOT EXISTS {$table_prefix}like (
    id bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    post_id bigint(20) NOT NULL,
    user_id bigint(20) NOT NULL,
        KEY recommenders (post_id, user_id)
) {$charset_collate};";

When a user clicks on a 'like' button on a WordPress post, a row gets added to the table which captures the user's ID and the post ID.

To get an array of all user IDs that have 'liked' a particular post I can do this:

$result = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM {$table_prefix}like WHERE post_id = %d", $post_id ) );

I'd now like to do 2 things:

  1. How can modify my query so that most recent rows added to the table are returned first in the $result array?

  2. How can I do exactly the same as question 1 but return 5 rows only?

  • 写回答

2条回答 默认 最新

  • dqnek0079 2014-05-13 20:02
    关注

    For 1: You can order them by your id in descending order by adding ORDER BY `id` DESC to the query.

    For 2: Add LIMIT 0, 5 aswell:

    $result = $wpdb->get_col( $wpdb->prepare( "SELECT `user_id` FROM `{$table_prefix}like` WHERE `post_id` = %d ORDER BY `id` DESC LIMIT 0, 5", $post_id ) );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?