简体   繁体   中英

Select from one table and count from another

I would like to know how to select from one table and count from another (loop) using a single query

Table ctagories

------------------------------
cat_id | cat_name | parent_id 
------------------------------
1      | General   | 0
------------------------------
2      | News      | 0
------------------------------
3      | Sports    | 1
------------------------------
4     | Test       | 0
------------------------------

Table posts

--------------------------------------
post_id| title     | c_id   | active
--------------------------------------
1      | test      | 1      |  1
--------------------------------------
1      | test 1    | 2      |  0
--------------------------------------
1      | test 2    | 1      |  1
--------------------------------------
1      | Test 3    | 3      |  1
--------------------------------------

I want display categories where parent_id=0 (main categories) with the post count (posts where active = 1 ) in front of it

Ex: General (2 posts)

Can anyone give me a example how to do it with a one query

SELECT 
    `cat_name`, 
    (SELECT COUNT(*) FROM `posts` p WHERE p.active =1 AND p.c_id = c.cat_id) as post_count 
FROM `category` c
WHERE c.parent_id = 0
ORDER BY `cat_name` ASC

try this query ,you can use subquery with select statement in query.

    select cat_name,
     (select count(*) 
      from post 
      where active=1 
      and c_id=cat_id
      ) as countpost 
    from ctagories 
    where parent_id=0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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