如何将另一个表中的其他列添加到复杂的SQL查询中?

时间:2019-05-18 10:29:19

标签: sql-server asp.net-mvc-4 visual-studio-2017 sql-server-2017

我正在尝试通过左连接将另一个表中的新列添加到旧查询中,但是抛出异常

我尝试使用左联接添加列,当我启动代码时会抛出异常

  

SqlException:找不到列“ m”或用户定义的函数或聚合“ m.military_status”,或者名称不明确。

代码:

string conditions = (militarystatus > 0 ? " AND t.military_status = " + militarystatus + " " : " "); 
// its just one elememt of condition, and also this parameter makes some error.

// this is my SQL query
string query = @"SELECT * 
                 FROM 
                     (SELECT 
                          t.*, 
                          ROW_NUMBER() OVER(ORDER BY t.students_sname + t.students_name) AS number  
                      FROM
                          (SELECT  
                               s.students_id, s.user_id, s.students_sname, s.students_name, 
                               s.students_father_name, s.students_birth_date, 
                               birth_country_id, country_id, 
                               s.students_curce_number, s.stage_id, 
                               s.edu_levels_id, s.education_form_id, 
                               s.faculty_id, s.speciality_id,
                               s.student_edu_status_id, s.payment_forms_id, 
                               s.lang_division_id, m.military_status
                               (CASE " + (settings.EduLevelCourseBoard.Where(x => x.IsFilter == true).Count() > 0 ? string.Join(" ", settings.EduLevelCourseBoard.Where(x => x.IsFilter == true)
                        .Select(y => " WHEN s.edu_levels_id in(" + y.EduLevelId + " ) and s.students_curce_number in(" + y.Course + @") then 1 ")) : " WHEN 1=1 THEN 0 ") + @" 
                              else 0
                        END
                    ) as Condition
                 FROM univer_students s left join Military_student_platoon_link m on s.students_id=m.student_id  WHERE DATEDIFF(YEAR, s.students_birth_date, getdate()) between " + settings.AgeFrom + " and " + settings.AgeTo + @" AND s.status=" + StatusModel.StatusNormal + @" AND m.military_status in (" + StatusModel.StatusNormal + @") and s.student_edu_status_id in(" + StudentEduStatusesModel.STATUS_NORMAL + @") 
                 and s.education_form_id in(" + string.Join(",", settings.EducatonForms) + @")  and s.edu_levels_id in(" + string.Join(",", settings.EduLevelCourseBoard.Where(x => x.IsFilter == true).Select(x => x.EduLevelId)) + @") and s.stage_id in(" + string.Join(",", settings.StageIds) + @")
                 )
                  as t where t.Condition=1 " + conditions + @" ) t2 ";
  

SqlException:找不到列“ m”或用户定义的函数或聚合“ m.military_status”,或者名称不明确。

0 个答案:

没有答案