mysql - 将多个表的计数连接到查询

时间:2012-11-03 11:16:51

标签: 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 ?

我该怎么办?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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