Search code examples
mysqlselectcomposite

Select statement across a join table


Have three tables that look like this:

PersonTable
Person.ID
Person.Name

PersonTypeCompositeTable
Person.ID
PersonType.ID

PersonTypeTable
PersonType.ID
PersonType.Category

For this example, say the values of PersonTypeCompositeTable are:

1,A
2,A
3,B

How to I write a SELECT statement that will return all the people with a PersonType of "A"?


UPDATE: (Working version of answer posted)

SELECT p.*
FROM PersonTable p
  INNER JOIN PersonTypeCompositeTable ptc
    ON p.ID = ptc.ID
  INNER JOIN PersonTypeTable pt
    ON ptc.ID = pt.ID
WHERE pt.Category = 'A'

Solution

  • You use joins between the three tables.

    SELECT p.*
    FROM PersonTable p
      INNER JOIN PersonTypeCompositeTable ptc
        ON p.Person.ID = ptc.Person.ID
      INNER JOIN PersonTypeTable pt
        ON ptc.PersonType.ID = pt.PersonType.ID
    WHERE pt.PersonType.Category = 'A'