【问题标题】:Query two tables with conditional order by in MYSQL在MYSQL中以条件顺序查询两个表
【发布时间】:2014-09-17 12:33:35
【问题描述】:

有两个看起来像的示例表

任务

编号 |标题 |用户 ID | ----|--------|---------| 1 |测试1 | 1 | 2 |测试2 | 1 | 3 |测试3 | 1 | 4 |测试4 | 1 | 5 |测试5 | 1 | 6 |测试6 | 1 | 7 |测试7 | 1 | 8 |测试8 | 1 | 9 |测试9 | 1 | 10 |测试10 | 2 |

回复

编号 |任务ID |状态 | -----|------------|------------| 1 | 2 |待定 | 2 | 2 |待定 | 3 | 2 |接受 | 4 | 2 |接受 | 5 | 2 |拒绝 | 6 | 2 |拒绝 | 7 | 3 |待定 | 8 | 4 |拒绝 | 9 | 5 |接受 | 10 | 6 |待定 | 11 | 6 |接受 | 12 | 7 |待定 | 13 | 7 |拒绝 | 11 | 8 |接受 | 12 | 8 |拒绝 |
  • 响应中的'task_id'是外键引用tasks.id

如果我想显示一个包含 user_id=1 的所有任务的表,列是:

  • 任务编号
  • 任务标题
  • 待处理响应的数量
  • 接受回复的数量
  • 拒绝回复的数量 此外,每一列都必须是可排序的,并且任务 ID 应该是不同的

在示例中,结果应该是:

任务ID |标题 |待定 |接受 |拒绝 ---------|--------|---------|----------|---------- 1 |测试1 | 0 | 0 | 0 2 |测试2 | 2 | 2 | 2 3 |测试3 | 1 | 0 | 0 4 |测试4 | 0 | 0 | 1 5 |测试5 | 0 | 1 | 0 6 |测试6 | 1 | 1 | 0 7 |测试7 | 1 | 0 | 1 8 |测试8 | 0 | 1 | 0 9 |测试8 | 0 | 0 | 0
  1. 如何查询一次才能得到这样的查询结果? (如果可能)

  2. 我尝试这样查询:

选择 `tasks`.*, count(`task_id`) 作为数字 来自“任务” left join `responses` on `responses`.`task_id`=`tasks`.`id` 其中 `tasks`.`user_id`=1 AND(`responses`.`status`='pending' 或 `responses`.`task_id` 为 NULL) 按 `tasks`.`id` 分组 按“编号”排序 限制 0,50

但是,这仅适用于“待处理”且无响应。同时,即使仅针对“待处理”,此查询也存在错误,那些具有 0 待处理响应但已接受或拒绝响应的任务通过此查询丢失。如何更正它以获得完整的任务列表?

感谢您的宝贵时间!

【问题讨论】:

    标签: mysql join sql-order-by


    【解决方案1】:

    您可以通过条件聚合来做到这一点:

    select t.*, sum(r.status = 'pending') as pending,
           sum(r.status = 'accepted') as accepted,
           sum(r.status = 'declined') as declined
    from `tasks` t left join
         `responses` r
          on r.`task_id`= t.`id`
    where t.`user_id` = 1 
    group by t.`id`
    order by accepted;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多