How to write SQL query for two foreign keys of the same table

  Question: How do we retrieve data from two tables when one of the tables has two foreign keys pointing to the other's primary key? For example, table A has two columns, Parent_ID and Child_ID. Table B has two columns, ID and Name. How do we retrieve data and have it displayed by Parent_ID, Parent_Name, Child_ID and Child_Name.
  A: Just concatenate the table twice. Once that's done, you'll have to use the table alias:
SELECT a.Parent_ID,bp.Name AS Parent_Name,a.Child_ID,bc.Name AS Child_Name
 FROM TableA AS a INNER JOIN TableB AS bp ON bp.ID = a.Parent_ID INNER JOIN TableB AS bc ON bc.ID = a.Child_ID
 
  Note that TableB appears twice in this query. This means that we must use the alias every time it occurs, and qualify the columns with the appropriate alias in the SELECT statement. Since the columns in the two instances of TableB have the same name, the name is common but not required - so we use the SELECT statement to duplicate the table alias.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326770317&siteId=291194637