Multiple Inner Joins - MySQL

Romulus

I have 2 tables, Task and Transaction, which look like this:

Task

enter image description here

Transaction

enter image description here

I would like to create a query which return information from both tables.

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

where:

  • 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

I tried with INNER JOIN but I get a wrong result:

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.

Taryn

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. Second. you should be able to get each of the total by using an aggregate function with some conditional logic, like a CASE expression:

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. Inside the CASE expression, you'll only get the total for each status.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related