Php,MySql从两个表中求和

时间:2016-03-22 04:58:15

标签: php mysql

我试图让这个查询有效:

SELECT 
  IFNULL(SUM(days), 0) AS days 
FROM
  `table_days` 
WHERE task = 1 
GROUP BY task 
UNION
ALL 
SELECT 
  IFNULL(SUM(total), 0) AS total 
FROM
  `table_total` 
WHERE task = 1 
GROUP BY task ;

我有两张桌子:

1. table_days

    id      task    days    
    ==========================
    1       1       3.00
    2       1       2.00


2. table_total
    id      task    total   
    ==========================
    1       3       0.00

上面的查询部分有效,结果是:

stdClass Object
(
    [days] => 5.00
)

但是我想从第二个表中得到结果,即使没有找到记录。像

这样的东西
stdClass Object
(
    [days] => 5.00
    [total] => 0.00
)

3 个答案:

答案 0 :(得分:1)

尝试此查询

SELECT 
  IFNULL(SUM(days), 0) AS days 
FROM
  `table_days` 
WHERE task = 1 
GROUP BY task 
UNION
ALL 
SELECT 
  SUM(case when task = 1 then IFNULL(total,0) else 0 end) AS total 
FROM
  `table_total` 
GROUP BY task ;

答案 1 :(得分:0)

您当前的方法存在的难题是UNION查询的后半部分没有"知道"关于上半年出现的任务的任何事情。  但是,加入这两个表将允许您利用两个表之间的关系。我认为更好的方法是LEFT JOIN table_days表格table_total,从而保留所有任务:

SELECT t1.task, t1.sum_days, t2.sum_total
FROM
(
    SELECT task, IFNULL(SUM(days), 0) AS sum_days
    FROM `table_days`
    GROUP BY task
) t1
LEFT JOIN
(
    SELECT task, IFNULL(SUM(total), 0) AS sum_total
    FROM `table_total`
    GROUP BY task
) t2
    ON t1.task = t2.task
WHERE t1.task = 1

如果要包含table_days表中的所有任务,可以删除WHERE子句。

答案 2 :(得分:0)

此代码适用于您(例如sqlfiddle):

SELECT
  IFNULL(SUM(days), 0) AS value, 'days' as name
FROM
  `table_days`
WHERE task = 1
GROUP BY task
UNION ALL

(SELECT CASE WHEN u.value = -1 then 0 else value end as value, 'total' as name
    FROM
    (
        SELECT
          IFNULL(SUM(total), 0) AS value
        FROM
          `table_total`
        WHERE task = 1
        GROUP BY task
        UNION
        SELECT -1 as value
    ) u
);

它将返回:

+-------+-------+
| value | name  |
+-------+-------+
|     5 | days  |
|     0 | total |
+-------+-------+