Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining database queries

Tags:

sql

mysql

How can these SQL-queries to extract statistics from my database be combined for better performance?

$total= mysql_query("SELECT COUNT(*) as number, SUM(order_total) as sum FROM history");
$month = mysql_query("SELECT COUNT(*) as number, SUM(order_total) as sum FROM history WHERE date >= UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -30 DAY))");
$day = mysql_query("SELECT COUNT(*) as number, SUM(order_total) as sum FROM history WHERE date >= UNIX_TIMESTAMP(CURDATE())");
like image 870
Sevenflash Avatar asked May 14 '26 14:05

Sevenflash


1 Answers

If you want to all the data in a single query, you have two choices:

  1. Use a UNION query (as sugested by bishop in his answer)
  2. Tweak a query to get what you need in a single row

I'll show option 2 (option 1 has been already covered).

Note: I'm using user variables (that stuff in the init subquery) to avoid writing the expressions again and again. Also, to filter the aggregate data, I'm using case ... end expressions.

select 
    -- Your first query:
    count(*) as number, sum(order_total) as `sum`
    -- Your second query:
  , sum(case when `date` <= @prev_date then 1 else 0 end) as number_prev
  , sum(case when `date` <= @prev_date then order_total else 0 end) as sum_prev
    -- Your third query:
  , sum(case when `date` <= @cur_date then 1 else 0 end) as number_cur
  , sum(case when `date` <= @cur_date then order_total else 0 end) as sum_cur
from (
         select @cur_date := unix_timestamp(curdate())
              , @prev_date := unix_timestamp(date_add(curdate(), interval -30 day))
     ) as init
   , history;

Hope this helps

like image 162
Barranka Avatar answered May 17 '26 03:05

Barranka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!