2

如何使用 mysqli 查询循环从两个表中选择和计数。

这是表结构

table1 = categories 
id | catname
-------------
1  | cat1
2  | cat2
3  | cat3

很快。

table2 =  articles
id | article | catid
---------------------
1  | art1    | 2
2  | art2    | 2
3  | art3    | 1
4  | art4    | 3

我需要这样显示

cat 1 - 1 articles
cat 2 - 2 articles
cat 3 - 1 articles

谁能指出我如何使用 mysqli 查询来做到这一点?

4

3 回答 3

4

如果您希望将其放在单个列中,则可以使用以下内容:

select 
  concat(c.catname, ' - ', a.Total, ' articles') list
from categories c
inner join
(
  select count(*) Total,
    catid
  from articles
  group by catid
) a
  on c.id = a.catid

请参阅带有演示的 SQL Fiddle

或者您可以在没有子查询的情况下执行此操作:

select 
  concat(c.catname, ' - ', count(*), ' articles') list
from categories c
inner join articles a
  on c.id = a.catid
group by c.catname;

请参阅SQL Fiddle with Demo。结果是:

|              LIST |
---------------------
| cat1 - 1 articles |
| cat2 - 2 articles |
| cat3 - 1 articles |
于 2013-03-06T13:11:47.053 回答
1

试试这个

SELECT 
    c.catname,
    COUNT(*)
FROM categories c
INNER JOIN articles a
    ON c.id = a.catid
GROUP BY 
    c.catname
于 2013-03-06T13:11:09.580 回答
0

试试这个:

SELECT CONCAT(C.catname, ' - ', A.articles, ' Articles')
FROM   categories C
       INNER JOIN articles A
         ON C.id = A.catid
GROUP  BY A.catid
ORDER  BY C.catname
于 2013-03-06T13:12:34.430 回答