1

Can I somehow ignore the post with the earliest date? With SQL or PHP?

SELECT subject, date 
FROM posts
WHERE id = $id
ORDER BY date DESC
while ($row = mysql_fetch_array($query)) {

Cheers

3
  • Could you describe the sample data & expected output? Commented Jun 26, 2009 at 18:50
  • You can write a sub-query that fetches the earliest date, and include it in the where clause. I wouldn't have the foggiest idea how to code it. Commented Jun 26, 2009 at 18:53
  • Hopefully, you don't have multiple rows sharing the same id. Commented Jun 26, 2009 at 18:57

4 Answers 4

4

You could probably write some convoluted sql to do it, or you could just do it in your php:

$first = true;
while ($row = mysql_fetch_array($query)) {
    if ( $first ) {
       $first = false;
       continue;
    }

    // Process rows here
}
Sign up to request clarification or add additional context in comments.

4 Comments

HA! I don't program much, and I think that's quite clever. Upvote for you.
If the requirements are as simple as just starting from the second row of the result, then I vote for an in-code solution as well.
Shouldn't the row processing be as a part of an "else"? Otherwise, line one will be processed just like the rest.
@GiladG - that's why you have the "continue" statement inside the if. It skips the rest of the loop and starts over at the beginning.
2

I've got nothing to test this with, but would this work?

SELECT subject, date 
FROM posts
WHERE id = $id
OFFSET 1
ORDER BY date DESC

Or for MySQL five compatibility as pointed out in the comments

SELECT subject, date 
    FROM posts
    WHERE id = $id
    LIMIT 1,18446744073709551615;
    ORDER BY date DESC

The large number was copied exactly from the MySQL docs.

2 Comments

Again untested here but that looks good to me, offset treats the first row as 0 and so this should start from the 2nd.
I don't think you can do that in mysql. From the manual (version 5.0): "For compatibility with PostgreSQL, MySQL also supports the LIMIT row_count OFFSET offset syntax". In other words, you can't use offset by itself.
1

Assuming date uniquely determines a row for a given id,

  SELECT subject, date 
    FROM posts
   WHERE id = $id
     AND date NOT IN
         ( SELECT MIN(date)
             FROM posts
            WHERE id = $id
         )
ORDER BY date DESC

1 Comment

For a bit mor3e clarity, I would use "Where date <> (Select Min(Date) ..." instead of "Where Date Not In... "
0

If you're using SQL 2005 or better, you could use the row_number function...

With MyCTE AS (
    SELECT subject, 
           date,
           RowNumber = ROW_NUMBER() OVER(ORDER BY date DESC)
    FROM   posts
    WHERE  id = $id)
SELECT *
FROM   MyCTE
WHERE  RowNumber > 1
ORDER BY date DESC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.