从总和成本的两个表中选择全部

时间:2016-09-22 07:29:42

标签: php mysql

我尝试从mysql数据库中的2个表中选择所有表,并在第二个表中选择总成本的总和 我有一个表名tbl_project包含

db_id db_projectname和其他专栏

 1        test
 2        test2
 3        test3

第二个表名tbl_activities包含

db_id   db_projectname  db_totalcost
1        test            200
2        test            300
3        test2           800

我想要的输出是

test  500
test2 800
test3  

我尝试这个查询,但它没有给我那个结果

    select tbl_project.db_id, tbl_project.db_projectname,tbl_project.db_location,tbl_project.db_client,tbl_project.db_transferredto,tbl_project.db_psd,tbl_project.db_pdd,tbl_project.db_duration,tbl_project.db_past,tbl_project.db_padd,tbl_project.db_aduration,tbl_project.db_percent,tbl_project.db_pnote,tbl_project.db_user,tbl_project.db_cpercentage,tbl_project.db_epercentage,tbl_project.db_mpercentage,tbl_project.db_status,tbl_project.db_offer,tbl_project.db_sheet,tbl_project.db_invoice,tbl_project.db_po,sum(tbl_activities.db_totalcost) as total_cost from tbl_project,tbl_activities where 
tbl_project.db_projectname=tbl_activities.db_projectname
它给了我 测试但是另一个项目的总和只有一个项目不是全部

2 个答案:

答案 0 :(得分:1)

您需要使用LEFT JOIN & GROUP BY

SELECT
    tbl_project.db_id,
    tbl_project.db_projectname,
    tbl_project.db_location,
    tbl_project.db_client,
    tbl_project.db_transferredto,
    tbl_project.db_psd,
    tbl_project.db_pdd,
    tbl_project.db_duration,
    tbl_project.db_past,
    tbl_project.db_padd,
    tbl_project.db_aduration,
    tbl_project.db_percent,
    tbl_project.db_pnote,
    tbl_project.db_user,
    tbl_project.db_cpercentage,
    tbl_project.db_epercentage,
    tbl_project.db_mpercentage,
    tbl_project.db_status,
    tbl_project.db_offer,
    tbl_project.db_sheet,
    tbl_project.db_invoice,
    tbl_project.db_po,
    sum(
        tbl_activities.db_totalcost
    ) AS total_cost
FROM
    tbl_project
LEFT JOIN tbl_activities ON tbl_project.db_projectname = tbl_activities.db_projectname
GROUP BY tbl_project.db_id

注意:

使用不aggregate的{​​{1}}函数(例如SUM,COUNT ..)将结果集折叠为单行。

答案 1 :(得分:0)

试试这个;

SELECT 
db_projectname.db_projectname,SUM(tbl_activities.db_totalcost) AS total_cost 
FROM db_projectname
LEFT JOIN tbl_activities 
ON 
db_projectname.db_projectname = tbl_activities.db_projectname
GROUP BY db_projectname.db_projectname