多个内部联接 - MySQL

时间:2015-01-13 17:03:10

标签: mysql pivot inner-join

我有两张表TaskTransaction,如下所示:

任务

enter image description here

交易

enter image description here

我想创建一个从两个表中返回信息的查询。

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

其中:

  • name = Task.name
  • priority = Task.priority
  • waiting = count(transaction.id)WHERE task.id = transaction.task and transaction.status = 1
  • error = count(transaction.id)WHERE task.id = transaction.task and transaction.status = 2
  • done = count(transaction.id)WHERE task.id = transaction.task and transaction.status = 3
  • total = count(transaction.id)WHERE task.id = transaction.task
  • status = task.status

我尝试使用INNER加入,但结果错误:

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。

2 个答案:

答案 0 :(得分:1)


    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 
    

BY Shahen Babayan

答案 1 :(得分:0)

现有查询存在一些问题。首先,您不能在任何列上将两个表连接在一起。您似乎可以加入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的总计。