mysql - MYSQL中条件order by查询两个表

标签 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. 我尝试执行这样的查询:

    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 个待处理响应但已接受或拒绝响应的任务通过此查询丢失。如何纠正它以获得完整的任务列表?

感谢您的宝贵时间!

最佳答案

您可以通过条件聚合来执行此操作:

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;

关于mysql - MYSQL中条件order by查询两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24959374/

相关文章:

java - 转换日期时间并插入 MySQL

php - CakePHP 3 属于多个具有默认值的列

mysql - ORDER BY Color with Hex Code 作为 MySQL 中的标准

SQLite 和自定义顺序

php - 将 PHP 5.6 代码迁移到 PHP 7.3 的正确步骤

Mysql 不返回插入行的正确 id

sql - SQL Server 2012 Express 中的另一个 LEFT OUTER JOIN 失败

sql - 如何在MySQL中进行FULL OUTER JOIN?

mysql - 连接 3 个相关表 mySql

mysql - 优化慢查询MySQL InnoDB(Doctrine2)