简体   繁体   中英

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'"));

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, eg, by $result['positive'] .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM