简体   繁体   English

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

[英]mysql - joining count on multiple tables to a query

I want to select columns from a table and a count bases on the join of another two table, how can I do it? 我想从一个表中选择列,并基于另外两个表的连接进行计数,我该怎么做?

this is my count query which I have written: 这是我写的计数查询:

   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 

and I want to join it to 我想加入

select item_id, item_name, item_price from items ?

how can I do it? 我该怎么做?

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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM