I have a query to return the most recent n posts per discussion (example below has n as 3).
SELECT x.group_discussion_id, x.comment, x.date_posted,
x.username, x.realname,
TO_DAYS(NOW()) - TO_DAYS(x.date_posted) AS date_posted_days
FROM (
SELECT gdp.group_discussion_post_id,
gdp.group_discussion_id, gdp.comment,
gdp.date_posted, m.username, m.realname,
@recent_post_rank := IF
(
@prev_discussion = gdp.group_discussion_id,
@recent_post_rank + 1,
1
) AS recent_post_rank,
@prev_discussion := gdp.group_discussion_id
FROM group_discussion_posts gdp
JOIN members m
ON m.memberid = gdp.memberid
WHERE gdp.active = 1
AND gdp.reply_to_post_id != 0
AND gdp.group_discussion_id IN (1, 2, 3)
ORDER BY gdp.group_discussion_id DESC,
gdp.group_discussion_post_id DESC
) x
WHERE recent_post_rank <= 3
This query works perfectly in MySQL, I have also run the $sth->{Statement}; output which runs the same.
However, running the query on my site, using DBI does not return the same output, it does not restrict the rows returned to the n value i.e. all of the matching group_discussion_posts are returned.
Debugging this I found that dbi returns the recent_post_rank as 1 for every row (unlike when it is run directly in MySQL), and there is no value for @prev_discussion
Therefore, it would appear that DBI is not properly handling this @prev_discussion stored value.
Any ideas?
my $sth = $dbh->prepare('SELECT x.group_discussion_id, x.comment,
+x.date_posted,
x.username, x.realname,
TO_DAYS(NOW()) - TO_DAYS(x.date_posted) AS date_posted_days
FROM (
SELECT gdp.group_discussion_post_id,
gdp.group_discussion_id, gdp.comment,
gdp.date_posted, m.username, m.realname,
@recent_post_rank := IF
(
@prev_discussion = gdp.group_discussion_id,
@recent_post_rank + 1,
1
) AS recent_post_rank,
@prev_discussion := gdp.group_discussion_id
FROM group_discussion_posts gdp
JOIN members m
ON m.memberid = gdp.memberid
WHERE gdp.active = 1
AND gdp.reply_to_post_id != 0
AND gdp.group_discussion_id IN (1, 2, 3)
ORDER BY gdp.group_discussion_id DESC,
gdp.group_discussion_post_id DESC
) x
WHERE recent_post_rank <= 3' );
$sth->execute();
return $sth->fetchall_arrayref();