简体   繁体   中英

Join two tables in MySQL, have just one row in the result set with few columns selected from second table

I am having a challenge to achieve the following

Have 2 tables namely Transaction Table and Transaction_Event_LOG_INFO table

Transaction Table Details

SL TXN_ID TXN_FOR TXN_TYPE
1 111 Shopping Debit
2 112 Rent Debit

Transaction_Event_LOG_INFO table

SL TXN_ID EVT_ID EVT_CODE EVT_CREATED_DT
1 111 200 100 11-12-2020 12:00:00
1 111 201 101 11-12-2020 12:01:00
1 111 202 102 11-12-2020 12:02:00
1 111 203 103 11-12-2020 12:03:00
1 111 204 104 11-12-2020 12:04:00
1 112 205 100 11-12-2020 12:05:00
1 112 206 101 11-12-2020 12:06:00
1 112 207 102 11-12-2020 12:07:00
1 112 208 103 11-12-2020 12:08:00
1 112 209 104 11-12-2020 12:09:00

I need to join the above two tables based on TXN_ID (which is unique) and have just one row for every TXN ID and having all columns from 1st table and just the EVT_CREATED_DT from 2nd table like where EVT_CODE=100 and 104

like below

SL TXN_ID TXN_FOR TXN_TYPE EVT_CREATED_DT_FOR_100 EVT_CREATED_DT_104
1 111 Shopping Debit 11-12-2020 12:00:00 11-12-2020 12:04:00
2 112 Rent Debit 11-12-2020 12:05:00 11-12-2020 12:09:00

You can do cnoditional aggregation:

select t.*, te.evt_created_dt_100, te.evt_created_dt_104
from transaction t
inner join (
    select txn_id
        max(case when evt_code = 100 then evt_created_dt end) as evt_created_dt_100,
        max(case when evt_code = 104 then evt_created_dt end) as evt_created_dt_104
    from transaction_event_log_info
    where evt_code in (100, 104)
    group by txn_id
) te on te.txn_id = t.txn_id

In very recent versions of MySQL, this would be more efficiently phrased with a lateral join:

select t.*, te.*
from transaction t
cross join lateral (
    select
        max(case when te.evt_code = 100 then te.evt_created_dt end) as evt_created_dt_100,
        max(case when te.evt_code = 104 then te.evt_created_dt end) as evt_created_dt_104
    from transaction_event_log_info te
    where te.evt_code in (100, 104) and te.txn_id = t.txn_id
) te

If you want to allow transactions that have none of the two events, you would change the inner join to a left join - and the cross join lateral (...) te to a left join lateral (...) te on true .

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