简体   繁体   English

Select 来自子查询的列

[英]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 output 计数如期而至

But now I have a new requirement to get additional column (D.Subject)in the data from the Details table但是现在我有一个新要求,即从 Details 表中获取数据中的附加列(D.Subject)

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.您应该在 select 中使用不同的值。 Dont really need the where condition, as that will be covered in your join condition.真的不需要 where 条件,因为这将包含在您的加入条件中。

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因为这些表之间可能有更多的连接条件,而不仅仅是列 student_id 到 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.因此,您要么找到正确的连接条件,要么区分这些值以保持密切联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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