我正在努力使这个查询工作:
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/