-1

Problem in simple words, 1st must be left joined to the 2nd table where the record is latest. So, I use an approach of using function MAX()

Currently I have 2 tables.

matches

enter image description here

matches_payments

enter image description here |

Now I want to join the second table to first one using MAX(id) on matches_payments

Desired result

enter image description here

but I am not getting desired result due to greatest-n-per-group problem.

Query

SELECT matches.id, mp.*
FROM matches
  LEFT JOIN (SELECT
               MAX(id) AS id,
               match_id
               paymentStatus
             FROM matches_payments
             GROUP BY match_id) AS mp ON mp.id = matches.id;

Desired result is not produced due to : Stackoverflow Question

When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same. FROM MySQL Dev

PS : I know the tables are poorly designed. It is not my work as the last developer did those.

Community
  • 1
  • 1
Rooshan Akthar
  • 401
  • 5
  • 14

1 Answers1

1

You need two joins. You need a self-join of the matches_payments table to get the row with the highest ID for each match_id, as shown in SQL Select only rows with Max Value on a Column. Then you LEFT JOIN this to matches to combine the two tables:

SELECT m.*, mp.paymentStatus, mp.paymentAmount
FROM matches AS m
LEFT JOIN (
    SELECT mp1.*
    FROM matches_payments AS mp1
    JOIN (SELECT match_id, MAX(id) AS id
          FROM matches_payments
          GROUP BY match_id) AS mp2
    ON mp1.match_id = mp2.match_id AND mp1.id = mp2.id
) AS mp ON mp.match_id = m.id
Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612