SQL self-referencing query. JOIN

那年仲夏 提交于 2019-12-22 10:54:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!