使用Join表获取Sum

时间:2013-01-04 19:03:20

标签: mysql select join group-by

如何使用查询SUM表获取JOIN查询,我有两个表,我的表是laporanlaporan_pengeluaran

table laporan

id  name    shell
9   loli    12000
10  ardi    24000
11  dian    5500

table laporan_pengeluaran

id  laporan_id  harga
1   9           15000
2   9           29000
3   10          7500
4   10          5000
5   11          3000
6   11          3000

我的问题,如何使用连接表获取SUM,在表laporan中按id / name分组,所以我想获得如下结果:

id  name    shell   harga
9   loli    12000   44000
10  ardi    24000   12500
11  dian    5500    6000

感谢。

4 个答案:

答案 0 :(得分:5)

您可以加入这两个表,然后sum(harga)来获取结果。如果您知道laporan表中的值始终为laporan_pengeluaran,那么您可以使用INNER JOIN

select l.id,
  l.name,
  l.shell,
  sum(lp.harga) harga
from laporan l
inner join laporan_pengeluaran lp
  on l.id = lp.laporan_id
group by l.id, l.name, l.shell

请参阅SQL Fiddle with Demo

如果laporan表中可能遗漏了laporan_pengeluaran个值,请使用LEFT JOIN

select l.id,
  l.name,
  l.shell,
  sum(lp.harga) harga
from laporan l
left join laporan_pengeluaran lp
  on l.id = lp.laporan_id
group by l.id, l.name, l.shell

请参阅SQL Fiddle with Demo

结果是:

| ID | NAME | SHELL | HARGA |
-----------------------------
|  9 | loli | 12000 | 44000 |
| 10 | ardi | 24000 | 12500 |
| 11 | dian |  5500 |  6000 |

答案 1 :(得分:0)

SELECT
  laporan.id AS id,
  laporan.name AS name,
  laporan.shell AS shell,
  IFNULL(SUM(laporan_pengeluaran.harga),0) AS harga
FROM laporan
LEFT JOIN laporan_pengeluaran ON laporan.id=laporan_pengeluaran.laporan_id

答案 2 :(得分:0)

尝试此查询

SELECT
    l.id,
    l.name,
    IFNULL(lp.TCount,0) as Total
FROM laporan as l   
LEFT JOIN (
            SELECT 
                laporan_id,
                SUM(harga) as TCount
            FROM    laporan_pengeluaran
            GROUP BY laporan_id
            ) as lp ON lp.laporan_id = l.id

答案 3 :(得分:0)

试试这个:

SELECT l.id, l.name, l.shell, SUM(lp.harga) harga 
FROM laporan l 
LEFT JOIN laporan_pengeluaran lp ON l.id = lp.laporan_id 
GROUP BY l.id; 

选中此SQL FIDDLE DEMO

输出

| ID | NAME | SHELL | HARGA |
-----------------------------
|  9 | loli | 12000 | 44000 |
| 10 | ardi | 24000 | 12500 |
| 11 | dian |  5500 |  6000 |