2012-11-03 2 views
1

테이블의 열을 선택하고 다른 두 테이블의 조인을 기준으로 계산을하고 싶습니다. 어떻게해야합니까?mysql - 쿼리에 여러 테이블의 수를 합산합니다.

이 내가 쓴 내 카운트 쿼리입니다 :

SELECT COUNT(*) AS num_review FROM approved_reviews m, reviews u where 
    m.review_id_=u.id and u.item_id =? and m.approved=1 

와 나는

select item_id, item_name, item_price from items ? 

내가 어떻게 할 수에 가입하려면?

답변

0
select items.item_id, item_name, item_price, COALESCE(t.cnt ,0)   
from items join (
        SELECT u.item_id , COUNT(*) cnt 
        FROM approved_reviews m, reviews u 
        WHERE m.review_id_=u.id and m.approved=1 
        GROUP BY u.item_id 
       ) t on items.item_id = t.item_id 
+0

이 경우에 0을 reurn makt 몇 가지 방법이 .... 그게 도움이되지만 더 검토가없는 경우는 NULL을 반환? – Yuval

+0

내 수정 된 쿼리에서와 같이 'COALESCE'사용 –

0
select * 
from 
(SELECT COUNT(*) AS num_review, u.item_id FROM approved_reviews m, reviews u where 
    m.review_id_=u.id and u.item_id =? and m.approved=1 group by u.item_id) count_sub, 
(select item_id, item_name, item_price from items) item_sub 
where item_sub.item_id = count_sub.item_id 
관련 문제