简体   繁体   中英

sql complex join

I have the three related tables that i would like to retrieve data from using joins: tbl_accounts containing the account details of users, tbl_users containing the personal details of users and tbl_t_records that contains the transaction details of all users.

In the tbl_accounts i have a foreign key column holder that helps link it to the tbl_users and in the tbl_t_records I have the foreign key columns oaccount and daccount each linking to tbl_accounts but the oaccount stores the details for the account from which the transaction originated while daccount stores the details for the account to which the transaction is destined

here is the snippet fro the tbl_accounts tabletbl_accounts 屏幕截图

Here is the one for tbl_users在此处输入图片说明

This is the one for tbl_t_records在此处输入图片说明

I would like to create a query that return the name of a sender, receiver and the transaction id using joins. so far this is what I have tried

    SELECT tbl_t_records.id transaction_id,
            CONCAT(tbl_users.lname,tbl_users.othername)as sender, 
            amount,
            CONCAT(tbl_users.lname,tbl_users.othername)as receiver 
    FROM tbl_t_records
        INNER JOIN tbl_accounts on oaccount = tbl_accounts.id 
        INNER JOIN tbl_users ON tbl_accounts.holder = tbl_users.id 

this does not give me the details of the destination account rather it only presents the data fro the sender that it uses as the same for the reciever as shown here在此处输入图片说明 What am I doing wrong?

You just need multiple join s -- a separate set for each name:

SELECT r.*,
       CONCAT(uo.lname, uo.othername) as sender,
       CONCAT(ud.lname, ud.othername) as receiver
FROM tbl_t_records r JOIN
     tbl_accounts ao
     ON r.oaccount = ao.id JOIN
     tbl_users uo
     ON ao.holder = uo.id JOIN
     tbl_accounts ad
     ON r.daccount = ad.id JOIN
     tbl_users ud
     ON ad.holder = ud.id;

You can join several times, as follows:

select 
    r.id transaction_id,
    concat(u1.lname, u1.othername) sender, 
    concat(u2.lname, u2.othername) receiver, 
    r.amount
from tbl_t_records r
inner join tbl_accounts a1 on a1.id = r.oaccount
inner join tbl_users u1 on u1.id = a1.holder
inner join tbl_accounts a2 on a2.id = r.daccount
inner join tbl_users u2 on u2.id = a2.holder

This query starts from the transaction table and then follows the relationships related to oaccount through tbl_accounts (aliased a1 ) to tbl_users (aliased u1 ). Another series of joins starts from daccount and brings the related user data (aliases a2/u2 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM