外连接多个表

时间:2014-12-07 14:40:55

标签: mysql sql database join

我想要加入4个表:

tbl_transaksi_header
--------------------
kode_transaksi
kode_user
nama_penerima
email_penerima
alamat_penerima
bank
telpon


tbl_konfirmasi
--------------------
id
kode
member
namarekening

tbl_user
-------------------
kode_user
username_user

tbl_transaksi_detail
---------------------
kode_transaksi
harga
jumlah
status

我想在nama_rek中显示包括NULL的所有数据。

我试过了:

SELECT t.status, t.kode_transaksi kode, u.username_user nama_user, t.nama_penerima penerima, t.telpon, t.bank, sum(d.harga*d.jumlah) total,k.namarekening nama_rek
FROM tbl_transaksi_header t
    JOIN tbl_user u
        ON t.kode_user=u.kode_user
    JOIN tbl_transaksi_detail d
        ON t.kode_transaksi=d.kode_transaksi
    LEFT OUTER JOIN tbl_konfirmasi k
        ON t.kode_transaksi=k.kode

工作正常,但没有显示null结果,只显示1行结果。我想要这样的东西:

status  kode    nama_user   penerima    telpn   bank    total   nama_rek
xxx     xxx     xxx         xxx         xxx     xxx     xxx     NULL
xxx     xxx     xxx         xxx         xxx     xxx     xxx     NULL
xxx     xxx     xxx         xxx         xxx     xxx     xxx     yyy
xxx     xxx     xxx         xxx         xxx     xxx     xxx     NULL

示例数据:

kode_transaksi  kode_user   nama_penerima   email_penerima  alamat_penerima bank    telpon
kd1             1           john            some@email.com  florida         Bank A  088833221
kd2             2           elsa            some@email.com  uk              Bank B  088833222
kd3             1           roy             some@email.com  manhattan       Bank C  088833223

id  kode    member  namarekening
1   kd1     paul    paul

kode_user   username_user
1           paul
2           elena

kode_transaksi  harga   jumlah  status
kd1             10      2       process
kd1             5       2       process
kd1             5       1       process
kd2             4       3       pending
kd2             3       4       pending
kd3             2       3       pending

我想要这个输出:

status  kode    nama_user   penerima    telpon      bank    total   nama_rek
process kd1     paul        john        088833221   Bank A  35      paul
pending kd2     elena       elsa        088833222   Bank B  24      NULL
pending kd2     elena       roy         088833223   Bank C  6       NULL

1 个答案:

答案 0 :(得分:0)

你的加入很好;问题是您的选择中没有SUM()而没有GROUP BY。试试这个:

SELECT  t.kode_transaksi kode, u.username_user nama_user, t.nama_penerima penerima, t.telpon, t.bank, sum(d.harga*d.jumlah) total,k.namarekening nama_rek
FROM tbl_transaksi_header t
    JOIN tbl_user u
        ON t.kode_user=u.kode_user
    JOIN tbl_transaksi_detail d
        ON t.kode_transaksi=d.kode_transaksi
    LEFT OUTER JOIN tbl_konfirmasi k
        ON t.kode_transaksi=k.kode
GROUP BY
    t.kode_transaksi, u.username_user, t.nama_penerima , t.telpon, t.bank,k.namarekening