douhui1630 2013-09-12 06:32
浏览 12
已采纳

PHP SQL有一个问题

This is my table, I should fetch the MAX (id) of each status_id.

id      status_id
10          1
11          1
12          2
13          2
14          2
15          4
16          4

So, I use this sql query, it works true and fetchs me all max ID.

select status_id, max(id) as max FROM `table` 
where status_id in (1,2,3,4) group by status_id

This sql command fetchs me 3 MAX id using while.

11, 14, 16....

You see, there is not any suitable id to 3rd status_id. And if there is not any suitable id to 3rd status_id just mark it as zero. So I want that sql will bring these results:

11, 14, 0, 16

  • 写回答

2条回答 默认 最新

  • dornc9470 2013-09-12 06:36
    关注

    You can create a subquery which basically has all the ID's you need and have a left join against it.

    SELECT  a.status_ID,
            IFNULL(MAX(b.id), 0) maxVal
    FROM    
            (
                SELECT 1 status_ID UNION ALL 
                SELECT 2 UNION ALL
                SELECT 3 UNION ALL
                SELECT 4 
            ) a
            LEFT JOIN `table` b ON a.status_id = b.status_id
    GROUP   BY a.status_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?