Query to fetch records in a join and with multiple filters

Viewed 34

I have the following query:

SELECT * FROM tableA
INNER JOIN tableB as tableBJoin on tableBJoin.tableAId = tableA.id 
INNER JOIN tableC as tableCJoin on tableBJoin.tableCId = tableC.id 
INNER JOIN (
              SELECT tableBId,status, createdAt, type
              FROM  tableD 
              WHERE (tableBId, createdAt, type) IN (
                SELECT tableBId,max(createdAt), type
                FROM tableD   
                GROUP BY tableBId, type )) AS tableDVerification
              ON 
         
        tableBJoin.id= tableDVerification.tableBId
              AND (slug = 'foo' and status = 'pending') AND tableDVerification.type = 'cip';

This query the existing identities that matches with the filters in the WHERE clause. The tables structure is the following:

Table A:

id - tableBId - createdAt

1 - 4 - 2010-10-10

Table B:

id - tableCId - createdAt

4 - 3 - 2010-10-10
5 - 1 - 2010-10-10

Table C:

id - slug - createdAt

4 - foo - 2010-10-10
5 - biz - 2010-10-10

Table D:

id - tableBId - status - type - createdAt

1 - 4 - approved - cip -2010-10-10
2 - 5 - pending  - cip -2010-10-11

What I need to achieve now it's to add one more filter there. So for example. If I have an identity with records in the tableB associated with the slug foo and biz, if I add a filter like slug = 'foo' and status = 'approved' and slug = 'biz' and status = 'pending', the query should return the identity.

How can I achieve this?

0 Answers
Related