简体   繁体   中英

Right JOIN with select result

I have 5 tables tb1, tb2, tb3, tb4 and tb5.

This the select query

SELECT c.COL1, f.COL2, SUM(a.colx1* l.clox2) AS COL3 
FROM tb1 c
  JOIN tb2 b ON (c.id = b.idC)
  JOIN tb3 l ON (b.id = l.idB)
  JOIN tb4 a ON (a.id = l.idA)
  JOIN tb5 f ON (f.id = a.idF) 
GROUP BY c.COL1, f.COL2

This the result of select query

+-----------+-------+-----------+
| COL1      | COL2  | COL3      |
+-----------+-------+-----------+
| project1  | FAM1  | 1250.251  |
| project1  | FAM2  | 2145.325  |
| project2  | FAM1  | 2146.152  |
| project3  | FAM2  | 1248.002  |
| project4  | FAM1  | 3201.684  |
| project4  | FAM2  | 7325.981  |
| project5  | FAM1  | 4657.684  |

But i want to display the result with this format if the projectx does not have FAMx

+-----------+-------+-----------+
| COL1      | COL2  | COL3      |
+-----------+-------+-----------+
| project1  | FAM1  | 1250.251  |
| project1  | FAM2  | 2145.325  |
| project2  | FAM1  | 2146.152  |
| project2  | FAM2  | NULL      |
| project3  | FAM2  | NULL      |
| project3  | FAM2  | 1248.002  |
| project4  | FAM1  | 3201.684  |
| project4  | FAM2  | 7325.981  |
| project5  | FAM1  | 4657.684  |
| project5  | FAM1  | NULL      |

this is my test with RIGHT JOIN it doesn't work! What am I missing ?

CREATE TEMPORARY TABLE tempt AS
   SELECT c.COL1, f.COL2, SUM(a.colx1* l.clox2) AS COL3 
    FROM tb1 c
      JOIN tb2 b ON (c.id = b.idC)
      JOIN tb3 l ON (b.id = l.idB)
      JOIN tb4 a ON (a.id = l.idA)
      JOIN tb5 f ON (f.id = a.idF) 
    GROUP BY c.COL1, f.COL2;
SELECT t.* FROM tempt t RIGHT JOIN tb5 f ON (f.COL2 = t.COL2)

structure of tab5 table

+----+--------+------+
| id | COL1   | COL2 |
+----+--------+------+
|1   | F1     | FAM1 |
|2   | F2     | FAM2 |
+----+--------+------+

Left or right joins cannot themselves create the extra relationships you want between all "project" and "FAM" values.

You need to construct the cross join to get all the rows you need.

SELECT c.COL1, f.COL2, t.COL3 
FROM tb1 c
CROSS JOIN tb5 f
LEFT JOIN tempt t ON t.COL1=c.COL1 and t.COL2=f.COL2

If tbl1.COL1 or tbl5.COL2 are not unique, you would need to add a SELECT DISTINCT

Or perhaps the whole thing can be rolled into:

SELECT c.COL1, f.COL2, SUM(a.colx1* l.clox2) AS COL3 
FROM tb1 c
  CROSS JOIN tb5 f
  LEFT JOIN tb2 b ON (c.id = b.idC)
  LEFT JOIN tb3 l ON (b.id = l.idB)
  LEFT JOIN tb4 a ON (a.id = l.idA and f.id = a.idF)
GROUP BY c.COL1, f.COL2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM