嵌套的SQL Select语句

时间:2018-11-20 05:15:26

标签: sql sql-server tsql

我在两个数据库中都有许多表,我想从中提取信息以显示在网页的网格中。

如果我运行以下sql,它可以正常工作,并且仅返回一行:

Select DISTINCT s.STUDENT#, s.SURNAME,s.GIVEN_NAME,ar.EN_EMAIL,ar.CAREGIVER_NO,i.GIVENNAME,i.SURNAME,i.EMAIL,i.EMAIL_BILLING,ax.CORR_PREFERENCE
      from 
            [PCSchool].[dbo].[STUDENT] s
        INNER JOIN  [PCSchool].[dbo].[ALUMREL] ar
            on s.STUDENT# = ar.CHILD#
        LEFT JOIN
                [PCSchool].[dbo].[IDENTITY] i 
            on ar.PARENT# = i.[MEMBER#]
        left join   [PCSchool].[dbo].[ALUMREL_EX] ax
            on ar.parent# = ax.PARENT#
    where  (ar.PARENT# <> ar.FAMILY_HASH) and ax.CORR_PREFERENCE = 1 and ar.EN_EMAIL = 'I' where s.STUDENT#=7282)

Result form above query for one user

我的问题是,我有另一个桌子,上面有一个学生名单,上面有一个柜台和一个拘留所。

List of Students and their detentions

我希望能够根据滞留表从一个表中提取上述电子邮件信息。每个学生的拘留表中的StudentCode和上表中的Student#都是相同的。

我不知道这是否可以通过SQL来完成,或者是否需要通过服务器端代码来完成。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用拘留桌的联接

Select DISTINCT s.STUDENT#, s.SURNAME,s.GIVEN_NAME,ar.EN_EMAIL,ar.CAREGIVER_NO,i.GIVENNAME,i.SURNAME,i.EMAIL,i.EMAIL_BILLING,ax.CORR_PREFERENCE,detentype,detentioncount
      from 
            [PCSchool].[dbo].[STUDENT] s
        INNER JOIN  [PCSchool].[dbo].[ALUMREL] ar
            on s.STUDENT# = ar.CHILD#
        LEFT JOIN
                [PCSchool].[dbo].[IDENTITY] i 
            on ar.PARENT# = i.[MEMBER#]
        left join   [PCSchool].[dbo].[ALUMREL_EX] ax
            on ar.parent# = ax.PARENT#
        left join Detention on Detention.studentcode=s.STUDENT#
    where  (ar.PARENT# <> ar.FAMILY_HASH) and ax.CORR_PREFERENCE = 1 and ar.EN_EMAIL = 'I' where s.STUDENT#=7282)

答案 1 :(得分:0)

将两个结果集结合起来会得到想要的东西吗?

select a.student#,a.email 
  from (<first_query>) a
  join students b
    on a.student#=b.studentcode