Php 从一个表中选择,从另一个表中计数
我想知道如何使用单个查询从一个表中进行选择并从另一个表(循环)中进行计数 表3Php 从一个表中选择,从另一个表中计数,php,mysql,mysqli,Php,Mysql,Mysqli,我想知道如何使用单个查询从一个表中进行选择并从另一个表(循环)中进行计数 表3 ------------------------------ cat_id | cat_name | parent_id ------------------------------ 1 | General | 0 ------------------------------ 2 | News | 0 ------------------------------ 3 |
------------------------------
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
--------------------------------------
我希望显示类别其中parent_id=0
(主类别),并在其前面显示post count(posts其中active=1
)
例:一般事务(2个员额)
有谁能给我一个如何使用一个查询的例子吗?试试这个查询,您可以在查询中使用带有select语句的子查询
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 cat_name,
(select count(*)
from post
where active=1
and c_id=cat_id
) as countpost
from ctagories
where parent_id=0;
我认为
groupby
和left-join
在这里工作得更快