0

I have a query I am using where I'm displaying the results in 3 different areas. One of the areas I want to not set a limit and two of them I want to limit them to one. I was thinking in the foreach of those specific two areas I could add the limits there. I'm just not sure how to do that, and if that's the best way.

Here is my query:

$comments_query = "SELECT * FROM airwaves_comments aw,users u WHERE u.id=aw.from_id AND aw.FROM_id=aw.to_id AND aw.from_id=".$profile_id." order by aw.created_on desc" ;

Here is are the results being displayed where I don't want a limit.

if ($airwave)
 {
 foreach ($airwave as $airwave_comment_row)
 {
// stuff
}
}

Here are the results being displayed where I want to limit to one:

if ($airwave && $profile_id == $session_id)
            {
                foreach ($airwave as $airwave_comment_row)
                {
                    echo "<div id='profile_airwave'>";
                    echo $airwave_comment_row['comment'];
                    echo "<br />";
                    echo "<span class='profile_airwave_info'>"; 
                    echo $airwave_comment_row['created_on'];
                    echo "</span>";
                    echo "</div>";
                }
}

Is this possible, for them to share the same query? Or do I have to write a new query?

thanks

LightningWrist
  • 937
  • 4
  • 20
  • 37
  • 1
    [`UNION ... LIMIT`](http://stackoverflow.com/questions/1415328/combining-union-and-limit-operations-in-mysql-query) – Jared Farrish May 31 '13 at 18:50
  • 2
    If you only want to display one of them once and all of them otherwise, load them all into an array (as you appear to have done) and if you only want one, just display `$airwave_comment_row[0]`, otherwise loop over all via `foreach`. In other words, if you only need one, there is no need for (and no logical purpose for) a `foreach` loop. – Michael Berkowski May 31 '13 at 18:50
  • You can apply the limit condition from query itself. – Nisam May 31 '13 at 18:57

2 Answers2

1

You can change your query like this,

$comments_query = "SELECT * FROM airwaves_comments aw,users u WHERE u.id=aw.from_id AND aw.FROM_id=aw.to_id AND aw.from_id=".$profile_id." order by aw.created_on desc" ;
if($profile_id == $session_id){
$comments_query .= " LIMIT 0,1"
}

OR You can try with the same logic you have

    if ($airwave && $profile_id == $session_id)
         $airwave_comment_row = $airwave[0];
         // takes the first row
    }else if($airwave){
    foreach ($airwave as $airwave_comment_row)
       {
        // stuff
       }
   }
Nisam
  • 2,275
  • 21
  • 32
0

I think you can do with with a UNION query, but you would need to check if that's the best approach - if it works.

I would check, but I don'y have access to a MySQL server at present.

(SELECT * FROM table WHERE category = 1)
UNION
(SELECT * FROM table WHERE category = 2 LIMIT 10)
UNION
(SELECT * FROM table WHERE category = 3)

Anthony.

Anthony Sterling
  • 2,451
  • 16
  • 10