duanche4578 2014-05-10 21:20
浏览 236

在两个表上使用JOIN的mySQL COUNT

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

  • 写回答

1条回答 默认 最新

  • douzi1117 2014-05-10 23:03
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来