如何获得三个表中的类别计数?

时间:2012-08-11 11:03:51

标签: php mysql sql

category  table 

-----------------------
catid  | catname
-------------------------

Deal table
------------------------
dealid |  name | catid |
-----------------------


Cement Table
-----------------------
cid |  cname  | catid
-----------------------

ordertable
---------------------
oid | oname | catid
---------------------

以上三个表使用我想获取catid的总数并通过desc clause.how使用命令来编写sql查询?

the result like this way

catid  catcount catname
-----------------------
1       20        xxx
2       19        YYY 

1 个答案:

答案 0 :(得分:1)

您可以使用union创建包含所有类别类别的子查询:

select  c.name
,       count(*) as TotalCount
from    (
        select  catid
        from    deal
        union all
        select  catid
        from    comment
        union all
        select  catid
        from    ordertable
        ) as lst
join    category c
on      c.catid = lst.catid
group by
        c.name
order by
        count(*) desc