SQL Select With Multiple References to Single Table

前端 未结 3 1736
悲&欢浪女
悲&欢浪女 2021-02-19 11:22

I have a SQL DB that contains multiple relational tables. There are some fields in the master table that reference another table multiple times. For example, say I have a data

3条回答
  •  情书的邮戳
    2021-02-19 11:47

    You need to use table aliases in order to join multiple copies of the same table:

       SELECT m.Name, 
              s1.Enumeration AS 'State1',
              s2.Enumeration AS 'State2'
         FROM MasterTable m
    LEFT JOIN StateTable s1 = s1.id = m.state1
    LEFT JOIN StateTable s2 = s1.id = m.state2
    

    An INNER JOIN requires that data is present - if not, the entire record is excluded. A LEFT JOIN is safer, like if the state1/2/3/etc allows NULLs...

提交回复
热议问题