2011-05-10 6 views
0

고유 정확히 같은 테이블 아니지만, 난 그냥 테이블 구조를 시뮬레이션하고 있습니다.쿼리 JOINS과 다음

Table - Columns 
Company - comp_id (primary), parent_id; 
Department - comp_id, emp_id, dept_id(primary); 

parent_id- one to many - comp_id; 

comp_id - one to many - dept_id; 

dept_id - one to many - emp_id; 


requirement is to retrieve parent_id, count(dept_id), count(emp_id) group by parent_id 

다음 쿼리를 시도했지만 성능을 저해 할 수있는 DISTINCT를 사용해야합니다.

SELECT c.parent_id, 
COUNT(DISTINCT c.comp_id), 
COUNT(d.emp_id) 
FROM company c 
LEFT JOIN department d ON c.comp_id = d.comp_id 
WHERE c.parent_id = ? 
GROUP BY c.parent_id; 

더 좋은 방법을 지정해주세요.

+0

당신은 당신이 원하는 결과를 게시 할 수 있을까요? – klox

+0

미안 해요, 난 당신을하지 않습니다. 필요한 열은 내가 사용한 쿼리에서 지정됩니다. – Firefox

+0

parent_id, count (dept_id) 및 count (emp_id) 만 검색 하시겠습니까? – klox

답변

0
SELECT c.parent_id,COUNT(d.dept_id),COUNT(DISTINCT(d.emp_id)) 
FROM company c LEFT JOIN department d ON c.comp_id = d.comp_id 
GROUP BY c.parent_id 
+0

이것은 DISTINCT를 사용합니다. 전체적인 목적은 몇 가지 해결 방법을 사용하여 피하는 것이 었습니다. – Firefox

+0

는 모든 피하려고'DISTINCT'를 사용하십니까? 'SELECT DISTINCT'를 시도하십시오. – klox

관련 문제