[英]Multiple Inner Joins - MySQL
I have 2 tables, Task
and Transaction
, which look like this: 我有2个表
Task
和Transaction
,如下所示:
Task 任务
Transaction 交易
I would like to create a query which return information from both tables. 我想创建一个查询,从两个表中返回信息。
Columns: name, priority, waiting, error, done, total, status
列:
name, priority, waiting, error, done, total, status
where: 哪里:
I tried with INNER
JOIN but I get a wrong result: 我尝试了
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;
Could you please help me creating this query? 您能帮我创建此查询吗? I'm getting the columns waiting, error, done, total with a count of all the transactions.
我正在等待的列,错误,完成,总计所有事务的计数。 Instead it should get the number of transaction WHERE task.id = transaction.task and transaction.status = 1,2,3.
相反,它应该获取WHERE task.id = transaction.task和transaction.status = 1,2,3的事务数。
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 沙亨·巴巴扬(Shahen Babayan)
A few issues with your existing query. 现有查询存在一些问题。 First, you aren't joining your two tables together on any column.
首先,您不会在任何列上将两个表连接在一起。 It looks like you can join on
task.id
and transaction.task
. 看来您可以加入
task.id
和transaction.task
。 Second. 第二。 you should be able to get each of the total by using an aggregate function with some conditional logic, like a CASE expression:
您应该能够通过使用带有一些条件逻辑的聚合函数(例如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;
This type of query is known as a PIVOT, it's where you take the values from your rows and converts them into rows. 这种查询称为PIVOT,在这里您可以从行中获取值并将其转换为行。 Inside the CASE expression, you'll only get the total for each
status
. 在CASE表达式中,您将只获得每个
status
的总数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.