2

I have the following query:

    SELECT 
      usp.user_id AS userId,
      usp.create_time AS create_time,
      ml.amount AS amount      
    FROM user_subscription_plan AS usp
            RIGHT JOIN product AS product ON product.id = usp.product_id            
            LEFT JOIN modification_log AS ml ON ml.subscription_id = usp.id         
    WHERE usp.id IN ('447482')

I have three tables, from which I need to select data.

My problem begins with the last LEFT join.

modification_log table could have no entries, but also it could have more entries. I want to select only the latest entry. With the above query, if I have 2 (or more) entries in the modification_log, I receive 2 identical results (repeated).

What I would like to get:

If there are no results in the modification_log, then it will return null. I think that is covered with LEFT JOIN. But also, in the case of many record, I would need to select the latest added one (amount)

I believe I might need a sub-query, but I fail to implement it.

Onkar Musale
  • 909
  • 10
  • 25
Amiga500
  • 5,874
  • 10
  • 64
  • 117

2 Answers2

3

You have to use a subquery for taking left join with modification_log table as

SELECT 
  usp.user_id AS userId,
  usp.create_time AS create_time,
  ml.amount AS amount      
FROM user_subscription_plan AS usp
  RIGHT JOIN product AS product ON product.id = usp.product_id            
  LEFT JOIN 
        (select * modification_log where subscription_id 
        IN ('447482') order by created_at desc LIMIT 1)
        AS ml ON ml.subscription_id = usp.id         
WHERE usp.id IN ('447482')

Note that the where clause in subquery select * modification_log where subscription_id IN ('447482') is the same as with the last where condition

Jeffy Mathew
  • 570
  • 4
  • 16
1

Just add a max condition after your left join to get the latest entry to be joined, like below-

LEFT JOIN modification_log AS ml ON ml.subscription_id = usp.id
where usp.id IN ('447482') and ml.id = (select max(id) from modification_log)
nice_dev
  • 17,053
  • 2
  • 21
  • 35