如何从WordPress数据库获取特定结果集中的第三个最后一个user_id?

时间:2015-09-26 16:19:08

标签: php mysql wordpress

在下表中, Apple 类别有三行。我要做的是在 Apple 类别中选择所有user_id,然后获取该类别的第三个user_id。

根据下面的示例数据,我想要的记录是user_id是2的位置。因为在同一类别之后还有两个用户。

id  user_id  category
1   2        apple
2   4        banana
3   6        apple
4   7        berry
5   8        apple

我的代码失败了。当我尝试使用$sql转储var_dump变量的内容时,我始终获得NULL

这是我的PHP代码:

<?php
$post_id = 180;
$category = apple; // the most popular word
$sql = $wpdb->get_results($wpdb->prepare(
    "SELECT e.user_id, COUNT(e.user_id) as count FROM (SELECT user_id, id FROM $table_name WHERE post_id=%d AND category=%s )e WHERE id < e.id",
    $post_id,
    $category
));
foreach ($sql as $value) {
    $user_id = $value->user_id;
    $count = $value->count;
    if ($count >= 2) {
        echo $user_id;     
    }
}
?>

1 个答案:

答案 0 :(得分:0)

问题出在您的查询中。约束WHERE id < e.id将不匹配任何行,因为您将e.ide.id进行比较,因为您的FROM子句中只有一个(临时)表。例如,2这种方式永远不会少于2

为了达到你想要的效果,需要计算user_id大于当前记录的所有记录,然后获得计数等于2的记录。你可以用以下查询:

select
    a.user_id,
    count(b.user_id) as count
from 
    $table a 
left join 
    $table b -- join with the same table
on 
    a.category = b.category 
on 
    a.post_id = b.post_id 
and 
    a.user_id < b.user_id -- matching only results where user_id are greater
where 
    a.category = %s 
and 
    a.post_id = %d
group by 
    a.user_id having count = 2; -- exactly 2 rows

您可以将上述查询与PHP代码一起使用。