问题
i need to query a self referencing relationship for unit prerequisites.
i know that you need to use two Joins, do i SELECT my column and then join it to itself ?
SELECT u.unit_code,
u.name + ' is a prerequisite of ' + u.name AS unit_prerequisite
FROM units AS u
so far that is what i have, not sure where my joins have to be made? not even sure if that first part is correct.
回答1:
You do this by joining the table to itself on the self-referencing column:
SELECT
u.unit_code,
u1.name + ' is a prerequisite of ' + u2.name AS unit_prerequisite
FROM
units AS u1
inner join units u2 on u2.RefId = u1.RefId
回答2:
You will need you JOIN
to itself, similar to this:
SELECT u1.unit_code,
u1.name + ' is a prerequisite of ' + u2.name AS unit_prerequisite
FROM units u1
INNER JOIN units u2
ON u1.id = u2.id
来源:https://stackoverflow.com/questions/10862633/sql-self-referencing-query-join