I need to join 2 tables using a 3rd table

  • I need to link 2 tables; table A and Table C.

    But the only way to do that is using a 3rd table, table B.

    Here are the Ids I need to link up:

    tableA contains appleId

    tableB contains appleId and fruitId

    TableC contains fruitId

    And here is my query...does this look like a good way of doing this?

    SELECT at.appleId, at.appleName, bt.fruitId, bt.processTitle, ct.fruitId,

    ct.farmId, ct.farmText

    FROM TableA at

    LEFT JOIN TableB bt ON bt.appleId = at.appleId

    LEFT JOIN TableC ct ON ct.fruitId = bt.fruitId

    Thanks!

    Magy

  • Yeah, that's a pretty standard many-to-many relationship.

    ----------------------------------------------------The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood... Theodore RooseveltThe Scary DBAAuthor of: SQL Server 2017 Query Performance Tuning, 5th Edition and SQL Server Execution Plans, 3rd EditionProduct Evangelist for Red Gate Software

  • The only thing I would add would be to make sure the joins are correct. Using outer joins (LEFT) will return all rows from TableA and only matching items from TableB/C (I am assuming that there cannot be entries in TableB that don't have matching rows in TableA and TableC).

    Jeffrey Williams
    Problems are opportunities brilliantly disguised as insurmountable obstacles.

    How to post questions to get better answers faster
    Managing Transaction Logs

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply