Php, MySql 从两个表求和

标签 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
)

最佳答案

试试这个查询

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 ;

关于Php, MySql 从两个表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36146400/

相关文章:

php - 无法让 UPSERT 在具有自动增量列和 FK 的 MYSQL 上工作

mysql - SQL : how to find one specific data

php - 停止 PHP if 语句覆盖下面的 CSS 语句?对 MySQL 正确吗?

Mysql在where子句中计算结果?

php - https://链接本身转到:443

php - Facebook API : Cannot register an achievement with facebook

php - 在用户访问网站一段特定时间后创建弹出窗口

mysql - 查询时间呈指数增长?

php - Laravel/Eloquent - 如何同时运行多个原始 SQL 语句?

javascript - WooCommerce 单一产品页面上的倒计时器,直到产品销售结束