alexx0186
alexx0186

Reputation: 1557

Can I make those three SQL queries fit into just one?

I want to count the number of positive, neutral, negative feedbacks.

I have those 3 queries that look very much alike. Is there a way I can put all this into one query? Or is it the most concise way of doing it?

Thanks in advance, regards.

$total_positive_seller = mysql_num_rows(mysql_query("SELECT id FROM feedback 
           WHERE seller='$user' AND feedback='positive'"));
$total_neutral_seller = mysql_num_rows(mysql_query("SELECT id FROM feedback 
           WHERE seller='$user' AND feedback='neutral'"));
$total_negative_seller = mysql_num_rows(mysql_query("SELECT id FROM feedback 
           WHERE seller='$user' AND feedback='negative'"));

Upvotes: 0

Views: 90

Answers (1)

Sirko
Sirko

Reputation: 74046

If you just want to count appearances, your use of mysql_num_rows is rather inefficient. It would be better to use the count(*) functionality of MySQL like in the following query:

SELECT feedback, count(*) AS `count` 
  FROM feedback 
  WHERE seller='$user' 
  GROUP BY feedback

This gives you something that should look like the following

feedback | count
----------------
positive |   12
neutral  |   8
negative |   3

You can afterwards parse this like any other query-result in a row-wise fashion.

EDIT

If you want to address each entry seperatly in your following code you can use something like the following. After this code you can reference all entries, e.g., by $result['positive'].

$qres = mysql_query( 'SELECT ...' );
$result = array();
while( $row = mysql_fetch_array( $qres ) ) {
  $result[ $row['feedback' ] ] = $row['count'];
}

Upvotes: 6

Related Questions