skip to Main Content

How I can merge this 2 querys to 1?

 $query1 = mysqli_query($_connect, 'SELECT `id` FROM `callers` ORDER BY `id` DESC LIMIT 1') or die();
 $result1 = mysqli_fetch_object($query1);

 $query2 = mysqli_query($_connect, 'SELECT SUM(`calls`) AS "total" FROM `callers`') or die();
 $result2 = mysqli_fetch_object($query2);

Now I have:

$result1->id for the last ID
and
$result2->total for a Sum of all calls

For that results I have 2 querys, my queation: Is it possible to run 1 query and have both result?

2

Answers


  1. You can join the two queries.

    $query = mysqli_query($_connect, '
        SELECT *
        FROM (
            SELECT `id` FROM `callers` ORDER BY `id` DESC LIMIT 1
        ) AS t1
        CROSS JOIN (
            SELECT SUM(`calls`) AS "total" FROM `callers`
        ) AS t2');
    $result = mysqli_fetch_object($query);
    

    You can then use $result->id and $result->total.

    Login or Signup to reply.
  2. Well, I’ve got to take back what I wrote before, because I think there is a more optimal way to combine these two queries:

    SELECT 
      MIN(`id`) AS `lowest_id`,
      SUM(`calls`) AS `total`
    FROM `callers`;
    

    Note that using MIN() gets the single lowest id, just like your first query does.

    However, unless you runs these queries tens or hundreds of time per second, you won’t notice a big improvement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search