2012-11-03 63 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

這會有所幫助,但在沒有審查它返回NULL ....是有某種方式來makt它在這種情況下reurn 0? – 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