簡體   English   中英

從一個表中選擇,從另一個表中計數

[英]Select from one table and count from another

我想知道如何使用一個查詢從一個表中進行選擇並從另一個表(循環)中進行計數

餐桌雜物

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

表帖子

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

我想要顯示類別where parent_id=0 (主要類別),其前面是帖子數( where active = 1帖子)

例如:一般(2個帖子)

誰能給我一個例子,如何用一個查詢

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

嘗試此查詢,您可以在查詢中將子查詢與select語句一起使用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM