Search code examples
sqlcorrelated-subquery

How to access TABLE C from TABLE A with meantiming values from TABLE B


We have table A, B and C

A

+----+-----+
| id | b_1 |
+----+-----+
|  1 |  51 |
|  2 |  52 |
|  3 |  53 |
|  4 |  54 |
+----+-----+

B

+----+-----+
| id | c_1 |
+----+-----+
| 51 |  71 |
| 52 |  72 |
| 53 |  73 |
| 54 |  74 |
+----+-----+

C

+----+--------+
| id | locked |
+----+--------+
| 71 |      1 |
| 72 |      0 |
| 73 |      0 |
| 74 |      1 |
+----+--------+

Now I want to do something like this:

SELECT * FROM WHERE (SELECT locked FROM C WHERE id = (SELECT c_1 FROM B WHERE id = b_1)) = 0

So the result of this pseudo code should be all the values of table A with the value locked = 0 in table C. But for this I have to jump over B and get the id pairs.

How can I do this?


Solution

  • You can use INNER JOINs between those tables :

    select a.*
      from tableA a
      join tableB b on b.id = a.b_1
      join tableC c on c.id = b.c_1
     where c.locked = 0;
    
    id  b_1
    2   52
    3   53
    

    which returns only the column values of TableA.

    Demo