结合数据库查询

时间:2015-09-18 19:01:33

标签: mysql sql

如何将这些从我的数据库中提取统计信息的SQL查询结合起来以获得更好的性能?

$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())");

2 个答案:

答案 0 :(得分:2)

如果您想要查询单个查询中的所有数据,您有两种选择:

  1. 使用UNION查询(as sugested by bishop in his answer
  2. 调整查询以获得单行所需内容
  3. 我会显示选项2(已经涵盖了选项1)。

    注意:我使用用户变量(init子查询中的内容)来避免一次又一次地写表达式。另外,要过滤汇总数据,请使用case ... end表达式。

    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;
    

    希望这有帮助

答案 1 :(得分:1)

由于查询具有相同的列结构,您可以要求MySQL将它们与UNION操作结合起来:

(SELECT 'total' AS kind, COUNT(*) as number, SUM(order_total) as sum FROM history~
UNION
(SELECT 'by-month' AS kind, COUNT(*) as number, SUM(order_total) as sum FROM history WHERE date <= UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -30 DAY)))
UNION
(SELECT 'by-day' AS kind, COUNT(*) as number, SUM(order_total) as sum FROM history WHERE date <= UNIX_TIMESTAMP(CURDATE()))