mcode
mcode

Reputation: 97

MySQL Join one table to other two tables

I have a MySQL database including following tables that used to maintain transactions of some documents.

tbl_documents Table

+----+---------+------+---------+
| id | file_no | name | subject |
+----+---------+------+---------+
|  1 | A/10    | F1   | a       |
|  2 | A/11    | F2   | b       |
|  3 | A/12    | F3   | c       |
|  4 | A/13    | F4   | d       |
+----+---------+------+---------+ 

tbl_requests

+----+-------------+----------------+---------------+
| id | document_id | requested_date | approved_date |
+----+-------------+----------------+---------------+
|  1 |           1 | 2019-12-01     | 2019-12-02    |
|  2 |           2 | 2019-12-08     | 2019-12-08    |
+----+-------------+----------------+---------------+

tbl_issues

+----+-------------+------------+
| id | document_id | issue_date |
+----+-------------+------------+
|  1 |           1 | 2019-12-05 |
|  2 |           2 | 2019-12-10 |
+----+-------------+------------+

I want to get the following / Desired output by joining above three tables.

Desired Output

+---------+------+---------+----------------+---------------+------------+
| file_no | name | subject | requested_date | approved_date | issue_date |
+---------+------+---------+----------------+---------------+------------+
| A/10    | F1   | a       | 2019-12-01     | 2019-12-02    | 2019-12-05 |
| A/11    | F2   | b       | 2019-12-08     | 2019-12-08    | 2019-12-10 |
+---------+------+---------+----------------+---------------+------------+

To do that, I used the following query

select tbl_documents.file_no, tbl_documents.name, tbl_documents.subject, requested_date, approved_date, tbl_issues.issue_date 
from tbl_documents            
right join tbl_requests on tbl_requests.document_id=tbl_documents.id
right join tbl_issues on tbl_issues.document_id=tbl_documents.id

But didn't get the expected output. Can anyone help ?

Upvotes: 0

Views: 39

Answers (1)

The Impaler
The Impaler

Reputation: 48865

Just use inner joins, as in:

select 
  d.file_no,
  d.name,
  d.subject,
  r.requested_date,
  r.approved_date,
  i.issue_date
from tbl_documents d
join tbl_requests r on r.document_id = d.id
join tbl_issues i on i.document_id = d.id

Upvotes: 1

Related Questions