这里我想得到两个表值的总和,我的表名是datas
和abc_datas
。首先,我获取datas
表的结果如下 -
$query1 = $this->db->query("SELECT *, SUM(amount) AS total_sum
FROM datas
WHERE user_id = $user_id")->row();
接下来,我按如下方式获取abc_datas
的结果 -
$query2 = $this->db->query("SELECT *, SUM(amount) AS total_sum
FROM abc_datas
WHERE user_id = $user_id")->row();
现在,我希望将这两个查询组合在一起,并通过组合total_sum
来返回总数。例如,如果第一个表的total_sum
是500
而第二个表是1000
,我希望输出为1500
,但只有第一个查询值被取出
这是我写的最后一个查询 -
$query = $this->db->query("SELECT *, SUM(amount) AS total_sum1
FROM datas
WHERE user_id = $user_id
UNION ALL
SELECT *, SUM(amount) AS total_sum2
FROM abc_datas
WHERE user_id = $user_id;")->row();
return $query;
我改变了我的查询,以获得所需的输出 -
$query =$this->db->query("SELECT
(SELECT SUM(amount) as total_sum1 FROM datas WHERE user_id=$user_id) + (SELECT SUM(amount) as total_sum2 FROM abc_datas WHERE user_id=$user_id) as total_sum,(SELECT SUM(agent_amount) as total_agent_amount1 FROM datas WHERE user_id=$user_id) + (SELECT SUM(agent_amount) as total_agent_amount2 FROM abc_datas WHERE user_id=$user_id) as total_agent_amount,(SELECT SUM(profit) as total_profit1 FROM datas WHERE user_id=$user_id) + (SELECT SUM(profit) as total_profit2 FROM abc_datas WHERE user_id=$user_id) as total_profit
FROM dual");
return $query->row();
答案 0 :(得分:0)
结果如下
$query = $this->db->query("SELECT SUM(amount) AS total_sum
FROM (SELECT amount FROM datas WHERE `user_id`=$user_id
UNION ALL
SELECT amount FROM abc_datas WHERE `user_id`=$user_id) s");
return $query->row();