从两个表中选择和计数

时间:2013-03-06 13:08:47

标签: php mysqli

如何使用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查询来做到这一点吗?

3 个答案:

答案 0 :(得分: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 with Demo

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

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 |

答案 1 :(得分:1)

试试这个

SELECT 
    c.catname,
    COUNT(*)
FROM categories c
INNER JOIN articles a
    ON c.id = a.catid
GROUP BY 
    c.catname

答案 2 :(得分: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