MySQL subquery in a join statement

Viewed 30

I have the following simplified schema definitions and following queries in both knex.js format and the output SQL format.

collateral_transactions_state table:

id state
1 BLOCKCHAIN_ENTRY
2 FILLER1
3 FILLER2

collateral_transactions_requests table:

request_id state_id
abc123 1

collateral_state_transition_times table:

state_id request_id transition_time
3 abc123 10:35:00
1 abc123 10:40:00
knex('collateral_transactions_requests as ctr')
    .select(
      'ctr.request_id',
      'ctr.state_id',
      's.state',
      'x.transition_time'
    )
    .leftJoin(
      knex('collateral_state_transition_times as cstt')
        .select('cstt.state_id as cstt_state_id', 'transition_time')
        .where({
          'cstt.request_id': 'ctr.request_id',
          'cstt.state_id': 'ctr.state_id',
        })
        .as('x'),
      'ctr.state_id',
      'x.cstt_state_id'
    )
    .join('collateral_transactions_state as s', 's.id', '=', 'ctr.state_id');
select
  `ctr`.`request_id`,
  `ctr`.`state_id`,
  `s`.`state`,
  `x`.`transition_time`
from
  `collateral_transactions_requests` as `ctr`
  left join (
    select
      `cstt`.`state_id` as `cstt_state_id`,
      `transition_time`
    from
      `collateral_state_transition_times` as `cstt`
    where
      `cstt`.`request_id` = `ctr`.`request_id`
      and `cstt`.`state_id` = `ctr`.`state_id`
  ) as `x` on `ctr`.`state_id` = `x`.`cstt_state_id`
  inner join `collateral_transactions_state` as `s` on `s`.`id` = `ctr`.`state_id`
where
  `state_id` in (1, 4, 6, 10)

returns the following:

[
  {
    request_id: '4a8c80b777a64f34',
    state_id: 1,
    state: 'BLOCKCHAIN_ENTRY',
    transition_time: null
  }
]

What I expect to happen is to get something like the following:

[
  {
    request_id: '4a8c80b777a64f34',
    state_id: 1,
    state: 'BLOCKCHAIN_ENTRY',
    transition_time: 10:40:00
  }
]

I've also tried this query where I've used an inner join as opposed to a left join on the subquery in which case I get back an empty set for the results of this query. In short, I'm trying to start with a request from the collateral_transactions_requests table, use the current state to join with the appropriate record from the collateral_state_transition_times table to get the time that the first record entered a given state, and then joining with the collateral_transactions_state table for a readable version of the current state. Thanks for the help.

0 Answers
Related