在MYSQL中查询具有条件顺序的两个表

时间:2014-07-25 15:35:19

标签: mysql join sql-order-by

有两个示例表,看起来像

任务

 id | title  | user_id |
----|--------|---------|
 1  | test1  |    1    |
 2  | test2  |    1    |
 3  | test3  |    1    |
 4  | test4  |    1    |
 5  | test5  |    1    |
 6  | test6  |    1    |
 7  | test7  |    1    |
 8  | test8  |    1    |
 9  | test9  |    1    |
 10 | test10 |    2    |

应答

 id  | task_id  |  status   |
-----|----------|-----------|
 1   |    2     |  pending  |
 2   |    2     |  pending  |
 3   |    2     |  accepted |
 4   |    2     |  accepted |
 5   |    2     |  declined |
 6   |    2     |  declined |
 7   |    3     |  pending  |
 8   |    4     |  declined |
 9   |    5     |  accepted |
 10  |    6     |  pending  |
 11  |    6     |  accepted |
 12  |    7     |  pending  |
 13  |    7     |  declined |
 11  |    8     |  accepted |
 12  |    8     |  declined |
  • ' TASK_ID'在回复中是外键引用tasks。id

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

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

在示例中,结果应为:

 task_id | title | pending | accepted | declined 
---------|-------|---------|----------|----------
    1    | test1 |    0    |    0     |    0
    2    | test2 |    2    |    2     |    2
    3    | test3 |    1    |    0     |    0    
    4    | test4 |    0    |    0     |    1
    5    | test5 |    0    |    1     |    0
    6    | test6 |    1    |    1     |    0
    7    | test7 |    1    |    0     |    1
    8    | test8 |    0    |    1     |    0
    9    | test8 |    0    |    0     |    0
  1. 如何进行一次查询以获得这样的查询结果? (如果可能的话)

  2. 我试图像这样进行查询:

  3.     select `tasks`.*, count(`task_id`) as number
        from `tasks`
        left join `responses` on `responses`.`task_id`=`tasks`.`id`
        where `tasks`.`user_id`=1 AND (`responses`.`status`='pending' or `responses`.`task_id` is NULL)
        group by `tasks`.`id`
        order by `number`
        limit 0,50
    

    但是,这只适用于待定的'没有回应同时,此查询中存在错误,即使只是“等待”,此查询中缺少那些具有0待处理响应但已接受或拒绝响应的任务。如何纠正它以获得完整的任务列表?

    感谢您的时间!

1 个答案:

答案 0 :(得分: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;