Skip to content
Advertisement

inner join with subquery results differs for these data sets

the above two table has foreignkey relation with wcd.id = cases.wcd_id, Lets consider the records related to wcd.wid 5865. The result should be grouped by reason_id with the condition max(cases.id)

I used the query below to achieve this and got the result as expected.

Result:

with the same query for 5684, the query returns 0 rows though there is data available for it. but I’m expecting the rows below.

What the issue with the query and what needs to be changed to get the result above for 5684.?

here is the sqlfiddle link

Advertisement

Answer

You need to look back at the wcd table to propery correlate, since you need the id of the row that has the “latest” reason per wid – and that column is not available in cases.

In MySQL 8.0, we would just use row_number()… but you tagged your question MySQL 5.6. I find that the simplest way to express this is with a correlated subquery:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement