2011-11-11 1 views
0

나는 그들의 종에 대한 몇 가지 정보와 함께 특정 수준의 동물을 선택하는 쿼리를 가지고 ...관련 레코드를 계산하는 두 개의 내부 조인이있는 행 수가 잘못되었습니다.

SELECT animals.id, animals.name, species.name, species.exlevel 
FROM `animals` 
INNER JOIN species ON animals.spid = species.id 
WHERE animal.level=1 

나는이 쿼리를 덧붙이려는 코멘트 테이블의 모든 코멘트의 개수를 포함 시키려하고있다. 각 동물. 그러나, 나는 그것을 할 수있는 최적의 방법을 찾을 수 없습니다. 다음은 분명히 작동하지 않지만 두 가지 별도의 쿼리를 수행하지 않고 내가 수행하려고하는 것입니다.

SELECT animals.id, animals.name, species.name, species.exlevel, COUNT(comments.id) 
FROM `animals` 
INNER JOIN species ON animals.spid = species.id 
INNER JOIN comments ON animals.id = comments.anid 
WHERE animal.level =1 
AND comments.type =2 
+0

그리고 두 개의 별도의 쿼리를하고 문제점은 무엇입니까? – NullUserException

+0

그것들은 효율적이지 않습니다 ... 왜냐하면 현재 쿼리에서 mysql_fetch_array를 반복하고 select 쿼리를 사용하여 코멘트를 계산합니다. 한 가지 쿼리로 이동하고 싶습니다. – 0pt1m1z3

답변

1
SELECT animals.id, animals.name, species.name, species.exlevel, COUNT(comments.id) 
FROM `animals` 
INNER JOIN species ON animals.spid = species.id 
LEFT JOIN comments ON animals.id = comments.anid AND comments.type =2 
WHERE animal.level =1 
GROUP BY animals.id, animals.name, species.name, species.exlevel 
+0

감사. 그게 효과가 있었지만 동물들만 모았습니다. 필드. – 0pt1m1z3

관련 문제