SELECT clause with self joining table

前端 未结 3 521
盖世英雄少女心
盖世英雄少女心 2021-01-15 18:12

Two tables:

//SKILL
SNAME
---------------------
C++
C#
C
JAVA

//REQUIRED
SNAME          REQUIRED
------------------------
C++               C
C#                     


        
相关标签:
3条回答
  • 2021-01-15 18:45

    Not the best solution but you can try like this:

    select * from srequired
    where sname='C++'
    UNION
    select * from srequired
    where sname in (select required from srequired where sname='C++')
    
    0 讨论(0)
  • 2021-01-15 19:01

    The join criteria

    ON sq.SNAME='C++'; 
    

    Does not relate the two tables (sq and sq1) , and limits the result set to sq.SNAME = 'C++', which is why you are gettig only SNAME = 'C++' in the output.

    The join would need to be as follows.

    ON sq.Requires = sq1.sName 
    

    Then in your Where clause you need to specify:

    WHERE sq.sNAME = 'C++'
    

    You will then have sq.sName with 'C++' in 2 lines. sq1.sName with 'c' in all columns. and sq1.Requires with 'Reading' and 'Writing'

    To get the result set in a single output you will have to use a UNION or a CTE. a UNION will give you the 2 levels you need. a CTE can give you n-levels. i.e if reading had another per-requisite.

    0 讨论(0)
  • 2021-01-15 19:03

    Use CTE to make it generic. Levels may go deeper than just 2. Use the following query to get required result.

    with cte
    As
    (
    Select SName, [Required] from courses where SName = 'C++'
    Union All
    Select courses.SName, courses.[Required] from courses 
       inner join cte on courses.SName = cte.[Required]
    )
    select * from cte
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题