I have a MySQL table called bb_posts used by a bbPress forum. It has an autoincrement field called topid_id and another field called topic_poster.
I'm trying to write a function that finds the "next post by the same author". So, for instance, say the user is on a particular page that displays topic 123. If you do a SQL query:
SELECT *
FROM `bb_topics`
WHERE `topic_poster` = 5
ORDER BY `topic_id` ASC
This might return the following rows:
topic_id topic_poster 6 5 50 5 123 5 199 5 2039 5
What I'd like to do is write a SQL query that returns these two rows:
topic_id topic_poster 50 5 199 5
This would be the row PRIOR to the row with topic_id of 123, and the row AFTER that row.
If it's too hard to do this in one query, it's definitely OK to break this up into two queries...
I'd like to avoid doing the whole SQL query ("SELECT * FROM bb_topics
WHERE topic_poster
= 5") and looping through the results, because the result set is sometimes huge.
Is this possible? :-)
You can use UNION to get the previous and next record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.
SQL Server LAG() is a window function that provides access to a row at a specified physical offset which comes before the current row. In other words, by using the LAG() function, from the current row, you can access data of the previous row, or the row before the previous row, and so on.
For example, by using the LEAD() function, from the current row, you can access data of the next row, or the row after the next row, and so on. The LEAD() function can be very useful for comparing the value of the current row with the value of the following row.
The DATEDIFF function can also be used in a WHERE clause as well as ORDER BY and HAVING clauses. The units of time available for the DATEDIFF are the same as those for the DATEADD function.
Next one:
SELECT * FROM `bb_topics`
WHERE `topic_id` =
(select min(`topic_id`) FROM `bb_topics` where `topic_id` > 123
and `topic_poster` = 5)
Previous one:
SELECT * FROM `bb_topics`
WHERE `topic_id` =
(select max(`topic_id`) FROM `bb_topics` where `topic_id` < 123
and `topic_poster` = 5)
Both:
SELECT * FROM `bb_topics`
WHERE `topic_id` =
(select min(`topic_id`) FROM `bb_topics` where `topic_id` > 123
and `topic_poster` = 5)
or `topic_id` =
(select max(`topic_id`) FROM `bb_topics` where `topic_id` < 123
and `topic_poster` = 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With