简体   繁体   中英

mySQL COUNT with JOIN on two tables

first of all, sorry, i'm not good in mySQL right now.

I've got 2 tables:

post_meta

id | post_id | page_num
4  | 161     | 14
3  | 160     | 9
2  | 159     | 3
1  | 158     | 16

And:

wp_posts

id  | date                 | parent_id
161 | 2013-08-28 13:53:48  | 160
160 | 2013-07-28 13:53:48  | 0
159 | 2013-04-28 13:53:48  | 158
158 | 2013-02-28 13:53:48  | 0

I want to know the sum of all page_nums for the posts where the date is 2013. The problem is that 1 single post got severals other post which got the parent_id from the parent post.

In this example the id 160 is the parent post in wp_posts and got a child post with the id 161. But it's the same single post.

The page_num from post_meta got the post_id from each post even it's a child. In this case it would be id 4 and 2 from post_meta since that are the latest saves for the parent posts 160 and 159.

So i only need to sum up only the page_nums for the latest (newest) child post .

My (very bad) try so far:

COUNT pagenum FROM wp_postmeta a WHERE wp_postmeta b post_id.b = parent_id.a AND DATE LIKE='2014' GROUP BY parent_id.b

I hope you understand the problem.

Thanks for your help in advance and

best regards

if you only have one level of child/parent relationship you can use something like below to grab 1)parents without child and 2)latest child of each parent using group by

SELECT meta.*
FROM post_meta meta
INNER JOIN
(SELECT parent.id FROM wp_posts parent      -- parent without child
 WHERE YEAR(date) = 2013 
      AND parent_id = 0 
      AND NOT EXISTS (SELECT 1 FROM wp_posts child
                  WHERE child.parent_id = parent.id)
 UNION
 SELECT max(id) FROM wp_posts               -- latest child
 WHERE YEAR(date) = 2013
 AND parent_id > 0
 GROUP BY parent_id
 )posts
ON posts.id = meta.post_id

sqlFiddle

Then you can sum page_num using SUM(meta.page_num) as whateverNameYouLike like in this sqlFiddle

Note: The above query is making the assumption that the id in wp_posts table will be largest for a lastest date, if this isn't the case you'll have to grab the max(date) , and id combination and look for latest entry that way. Which shouldn't be too complex.

I also added an entry 162 with no child to test for cases of posts that have no children. That's why the sum of page_num is 18 instead of 17.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM