多个内部联接 - MySQL

Multiple Inner Joins - MySQL

我有 2 个表,TaskTransaction,它们看起来像这样:

任务

交易

我想创建一个查询,其中 return 来自两个表的信息。

列:name, priority, waiting, error, done, total, status

其中:

我尝试使用 INNER JOIN 但我得到了错误的结果:

SELECT tk.name, tk.priority, waiting.waiting, error.error, done.done, total.total
  FROM task AS tk, transaction AS tran
  INNER JOIN (
    SELECT count(id) AS waiting
    FROM transaction
    WHERE status = 1
  ) AS waiting
  INNER JOIN (
    SELECT count(id) AS error
    FROM transaction
    WHERE status = 3
  ) AS error
  INNER JOIN (
    SELECT count(id) AS done
    FROM transaction
    WHERE status = 4
  ) AS done
  INNER JOIN (
    SELECT count(id) AS total
    FROM transaction
  ) AS total;

你能帮我创建这个查询吗?我正在等待、错误、完成、总计所有交易的列。相反,它应该获取交易数量 WHERE task.id = transaction.task 和 transaction.status = 1,2,3。

您现有查询的一些问题。首先,您不会在任何列上将两个表连接在一起。您似乎可以加入 task.idtransaction.task。第二。您应该能够通过使用具有某些条件逻辑的聚合函数来获得每个总数,例如 CASE 表达式:

SELECT tk.name, tk.priority,
    sum(case when tran.status = 1 then 1 else 0 end) waiting,
    sum(case when tran.status = 3 then 1 else 0 end) error,
    sum(case when tran.status = 4 then 1 else 0 end) done,
    count(*) total
FROM task AS tk
INNER JOIN transaction AS tran
    ON tk.id = tran.task
GROUP BY tk.name, tk.priority;

这种类型的查询称为 PIVOT,您可以在其中从行中获取值并将它们转换为行。在 CASE 表达式中,您只会得到每个 status.

的总数

    select task.name,
               task.priority ,
                 count(tw.id) as waiting ,
                 count(te.id) as error,
                 count(td.id) as done,
                 count(task.id) as total,
                 task.status
        from transaction as tr
                    JOIN task 
                        on task.id = tr.task 
        left  JOIN task as tw
                        on ( tw.id = tr.task and tr.status = 1)
        left  JOIN task as te 
                        on ( te.id = tr.task and tr.status = 2)
        left  JOIN task as td 
                        on ( td.id = tr.task and tr.status = 3)
        group by task.id 
    

作者:沙亨巴巴彦