group by +left join +count (1) 쿼리 인스턴스

5000 단어
오늘 새로운 기능 개발을 해서 프로젝트를 다운로드하고 다운로드한 다음에 다음 데이터베이스 조회 문장을 볼 수 있습니다.
public Map<String, Object> queryConsultTotalList(ConsultParamVo vo,
			PageRequest pageRequest) {
		String proCountSql = "select doctorid, isproblem, count(1) rn from jkmh_webcms.tcm_consult where 1 = 1";

		String filterSql = "";

		proCountSql += " group by doctorid, isproblem";

		String totalSql = "select t.id,t.org_name, t.dept_name, t.emp_no, t.name, t.sex, nvl(sum(t.consult), 0) consult, nvl(sum(t.reply), 0) reply"
				+ " from (select d.id, d.org_name, d.dept_name, d.emp_no, d.name, (case when d.sex = '1' then ' ' else ' ' end) sex, c1.rn consult, c2.rn reply from jkmh_webcms.TB_DOCTOR_USERS d"
				+ " left join ("
				+ proCountSql
				+ ") c1 on d.id = c1.doctorid and c1.isproblem = '0'"
				+ " left join ("
				+ proCountSql
				+ ") c2 on d.id = c2.doctorid and c2.isproblem = '2') t where 1 = 1";

		totalSql += filterSql;

		totalSql += " group by t.id, t.org_name, t.dept_name, t.emp_no, t.name, t.sex";

		String countSql = "select count(1) from (" + totalSql + ")";

                int num = (pageRequest.getPageNo() - 1) * pageRequest.getPageSize();

		List list = dao.createSQLQuery(totalSql, null, null, null)
				.setFirstResult(num).setMaxResults(pageRequest.getPageSize())
				.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();

		int count = Integer.valueOf(dao
				.createSQLQuery(countSql, null, null, null).list().get(0)
				.toString());}

두 개의 데이터베이스 쿼리 문이 주로 사용되고 있음을 알 수 있습니다.
1、totalSql
2、countSql
그러나 대학 데이터베이스를 제대로 배우지 못한 나는 이런 약간 긴 데이터베이스 문장을 보고 어리둥절해져서 스스로 도대체 신마의 뜻을 잘 연구할 수밖에 없었다
먼저 totalsql 문을 데이터베이스에서 실행할 수 있는 문으로 복원합니다.
select t.id,t.org_name, t.dept_name, t.emp_no, t.name, t.sex, nvl(sum(t.consult), 0) consult, nvl(sum(t.reply), 0) reply from 
       (
          select d.id, d.org_name, d.dept_name, d.emp_no, d.name, (case when d.sex = '1' then ' ' else ' ' end) sex,
          c1.rn consult, c2.rn reply  from  jkmh_webcms.TB_DOCTOR_USERS d
          left join ( select doctorid , isproblem,count(1) rn from jkmh_webcms.tcm_consult group by doctorid, isproblem) c1
          on d.id = c1.doctorid and c1.isproblem ='0'
          left join ( select doctorid, isproblem, count(1) rn from jkmh_webcms.tcm_consult group by doctorid, isproblem) c2 
          on d.id = c2.doctorid and c2.isproblem = '2'
        )t  group by t.id, t.org_name, t.dept_name, t.emp_no, t.name, t.sex

분석은 다음과 같습니다.
1. 우선 우리는 중간의 괄호() 부분을 생략하면 다음과 같이 된다.
 select t.id,t.org_name, t.dept_name, t.emp_no, t.name, t.sex, nvl(sum(t.consult), 0) consult, nvl(sum(t.reply), 0) reply from t    group by t.id, t.org_name, t.dept_name, t.emp_no, t.name, t.sex
이렇게 하면 조회의 필드가 t표에서 온 id, org 를 포함하는 것을 뚜렷하게 볼 수 있다.name、dept_name、emp_no,name,sex 이건 잘 보여요.
다른 두 필드 nvl(sum(t.consult), 0)consult와 nvl(sum(t.reply), 0)reply는 나처럼 못 알아보는 사람이 있을 거라고 생각합니다. 자료를 찾아보면 구체적인 뜻을 알 수 있습니다.
다음은 nvl(sum(t.consult),0)consult가 도대체 무슨 뜻인지 상세히 소개하겠습니다. 우리는 외부에서 내부로 말합니다. 1. 먼저 nvl()는 하나의 함수입니다. (1) 함수 형식: NVL(string1,replace with)(2) 함수 기능:string1이NULL이면 NVL 함수가replace 로 되돌아옵니다.with의 값, 그렇지 않으면 원래의 값을 되돌려줍니다. nvl 함수에는 두 개의 인자가 있음을 알 수 있습니다.string1=sum(t.comsult) 두 번째 인자는replace 입니다.with=0; 그러면 nvl(sum(t.consult), 0)consult는sum(t.consult)가 비어 있을 때 0을 필드consult로 되돌려주는 값입니다.sum(t.consult)가 비어 있지 않으면 sum(t.consult)의 값을 필드consult로 되돌려줍니다
2. 그리고sum() 함수를 소개한다. (1), 함수 형식: SUM(열명)(2), 함수 작용: 수치 열의 총수를 되돌려준다.
3. consult는sumt(t.consult)의 별명
4、group by t.id, t.org_name, t.dept_name, t.emp_n,t.name,t.sex 이 구절은 주로 그룹 by의 용법과 관련된다. 내가 전편에서 전재한 그룹 by의 용법을 참고하면 이 구절의 뜻을 알 수 있다. 먼저 id에 따라 그룹을 나누고 id에 따라 그룹을 나누는 토대에서 각 그룹에서 org 를 누르는 것이다.name 그룹, 순서대로 유추합니다.
<여기서는 내가 주의해야 할 점을 기록하고 싶다. *******: 그룹 by 자구는 집합 함수에 맞추어 사용해야 한다. 그리고 집합 함수에 맞추어 사용할 때 그룹 by 자구에 집합 함수에 열 이름을 붙이지 말아야 한다. (as가 들어가면) 상세 참조 연결: 링크를 클릭하고 이어서 괄호 안의 조회 문구를 살펴보자. select d.id, d.orgname, d.dept_name, d.emp_n, d.name, (case when d.sex ='1'then'남자'else'여자'end) sex, c1.rn consult, c2.rn reply  from  jkmh_webcms.TB_DOCTOR_USERS d           left join ( select doctorid , isproblem,count(1) rn from jkmh_webcms.tcm_consult group by doctorid, isproblem) c1           on d.id = c1.doctorid and c1.isproblem ='0'           left join ( select doctorid, isproblem, count(1) rn from jkmh_webcms.tcm_consult group by doctorid, isproblem) c2            on d.id = c2.doctorid and c2.isproblem ='2'1, select 뒤에 조회하는 필드는 주로 세 장의 테이블에서 나온다. 각각 d표(id, org name, dept name,emp no,name,sex).c1표(rn 필드는consult로 이름 바꾸기) c2표(rn 필드는reply로 이름 바꾸기)는 주로 d표 왼쪽 연결 c1표가 왼쪽 연결 c2표에서 t표를 형성한다.
count(1)rn은 테이블 jkmhwebcms.tcm_consult의 값은 doctorid, isproblem에 따라 그룹을 나누고, 그룹을 나눈 후 그룹의 통계값count (1) 을 rn으로 이름을 바꿉니다.

좋은 웹페이지 즐겨찾기