简体   繁体   中英

Select A column from Subquery

I have a query like below

Select Student_ID, Name, School
From Student S
Where S.Student_ID in ( select associate_id from Details D)

The output count is coming as expected

But now I have a new requirement to get additional column (D.Subject)in the data from the Details table

Select S.Student_ID, S.Name, S.School, D.Subject
From Student S
Where  S.Student_ID in ( select associate_id from Details D)

When I'm trying to achieve the above by using the join like below the count is not matching. I tried both Left outer and inner join and the count doesn't come out correctly.

Select S.Student_ID, S.Name, S.School, D.Subject
From Student S
Left outer join Details D on S.Student_ID = D.associate_id
Where S.Student_ID in ( select associate_id from Details D)

Please let me know how to achieve this

Since we dont have the sample data, I tried to put something together based on your question

problem is with the distinct count. You should use distinct values in select. Dont really need the where condition, as that will be covered in your join condition.

Select distinct S.Student_ID, S.Name, S.School, D.Subject
From Student S join Details D on S.Student_ID = D.associate_id;

this will give you the unique counts there are. As there may be more join conditions between these tables and not just the column student_id to associate_id

for ex- If i take the example below

学生表 and详细信息 in line query will give you a different count then inner join.

So either you find a correct join conditions or distinct the values to keep you close.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM