0

How to use mysqli_fetch_array() for these 3 queries in the same table? or how to make this 3 query in to 1 query?

SELECT clinic,AVG(rating) FROM review GROUP BY clinic ORDER BY clinic
SELECT clinic,COUNT(rating) AS die FROM review WHERE rating = 1 GROUP BY clinic
SELECT clinic,COUNT(rating) AS normal FROM review WHERE rating = 7 GROUP BY clinic
ndrwnaguib
  • 4,539
  • 2
  • 26
  • 47

2 Answers2

1

You could use case expressions to move the condition in the last two queries to expressions that are counted. count skips nulls, so just use an expression that only returns something for the condition you want to count:

SELECT   clinic, 
         AVG(rating),
         COUNT(CASE rating WHEN 1 THEN 1 END) AS die,
         COUNT(CASE rating WHEN 7 THEN 1 END) AS normal
FROM     review
GROUP BY clinic 
ORDER BY clinic
Mureinik
  • 277,661
  • 50
  • 283
  • 320
0

You can use mysqli::multi_query. As an example,

$query  = "SELECT CURRENT_USER();"; # Example Query
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; # Second Example Query

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();

Since StackOverflow is not a code writing service, I am not going to write how this is going to happen in your case. Try to reflect it to your code, when you face problems, post a question.

Note: Example is from the link provided of the whole documentation of mysqli::multi_query.

Good Luck!

ndrwnaguib
  • 4,539
  • 2
  • 26
  • 47
  • IMHO, multi-query is almost never the right solution. There's little gained from it over just calling `mysqli_query()` separately for each query, and it just makes fetching the results more complicated. – Barmar Dec 23 '17 at 00:44
  • yes,but it good to know what multi-query look like ^.^ – Zizero Kub Dec 23 '17 at 01:40