duanmie9682 2015-12-11 19:57 采纳率: 100%
浏览 88

mysql查询:查询嵌套(?)

hi here's my data structure:

categories
id   name
----------------
1    dogs    
2    cats
3    birds

images
id   name   cat  datetime     views
---------------------------------------
1    dog1   1    2015-10-01   123
2    dog2   1    2015-10-02   45
3    cat1   2    2015-10-03   678
4    cat2   2    2015-11-01   901
5    cat3   2    2015-11-02   234
6    bird1  3    2015-12-03   456

i want to output: all categories and each category should show:

  • amount of images
  • maximum amount of views
  • date of latest image
  • id of latest file

desired output:

cat  name     images  views   latest       id_latest
----------------------------------------------------
1    dogs     2       123     2015-10-02   5
2    cats     3       901     2015-11-02   4
3    birds    1       456     2015-12-03   6

my query so far:

Select
  categories.*,
  Count(images.id) As images,
  Sum(images.views) As views,
  Max(images.datetime) As latest

From
  categories 
  Left Join images On images.catid =  categories.id 
Group By
  categories.id

the problem is: how would i get the last field id_latest?

thanks

  • 写回答

2条回答 默认 最新

  • duanci6484 2015-12-11 20:33
    关注

    Your tables are must be this :

    categories
    catid   name
    ----------------
    1    dogs    
    2    cats
    3    birds
    
    images
    imgid   name   catid  datetime     views
    ---------------------------------------
    1    dog1   1    2015-10-01   123
    2    dog2   1    2015-10-02   45
    3    cat1   2    2015-10-03   678
    4    cat2   2    2015-11-01   901
    5    cat3   2    2015-11-02   234
    6    bird1  3    2015-12-03   456
    

    And code :

     Select
      categories.catid,
      categories.name,
      Count(images.imgid) As images,
      Sum(images.views) As views,
      Max(images.datetime) As latest
    
    From
      categories 
      Left Join images On images.catid =  categories.catid 
    Group By
      categories.catid, categories.name
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?