在下面的表中,类别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
$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;
}
}
?>
问题在您的查询中。约束WHERE id < e.id
将不匹配任何行,因为您将e.id
与e.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