mysql - sql counting all records belong to parent record with many to may relationship -


i have tables called category , posts. post can belong more one category. category has many posts , relationship many many. created new weak entity cat_post table. in category, record can have many child not child of child. want count posts belongs parent records.

category table fields

id    category_id 1 2 3        4       1 5       1 6       2 7       2 

posts table

id  1 2 3 

cat_post table field

tender_id   category_id 1               4 2               5 3               3 3               5 4               6 4               4 

category:

+-----------------+--------------+------+-----+---------+----------------+   | field           | type         | null | key | default |          |   +-----------------+--------------+------+-----+---------+----------------+   | id              | int(11)      | no   | pri | null    | auto_increment |   +-----------------+--------------+------+-----+---------+----------------+   | category_id     | int(11)      | no   | null | null   |      null      |   +-----------------+--------------+------+-----+---------+----------------+   

posts:

+-------------------+--------------+------+-----+---------+-----------+   | field             | type         | null | key | default |     |   +-------------------+--------------+------+-----+---------+-----------+   | id                | int(11)      | no   | pri | null    |           |   +-------------------+--------------+------+-----+---------+-----------+   

cat_post:

+---------------+---------+------+-----+---------+-------+   | field         | type    | null | key | default | |   +---------------+---------+------+-----+---------+-------+   | category_id   | int(11) | no   | pri | null    |       |   | post_id       | int(11) | no   | pri | null    |       |   +---------------+---------+------+-----+---------+-------+   

i want count posts belongs parent records. in other word count posts each parent record of category category.category_id null only.
nb: if category record has child there no post record.

as understand it, work requirement:
(in example tender_id named post_id)

select c.id, count(p.id) postcount  category c inner join cat_post cp on c.id = cp.category_id  inner join posts p on p.id = cp.post_id c.category_id null group c.id 

this join tables , select records parent (no category_id in categories). groups result category.id, , count every post each category.

here example on sqlfiddle.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -