I have to write a single select query to fetch all details from seven tables. Earlier I had separate queries but now I am working on optimizing the queries. The following is my table structure :
Main Table (SN, model , regId) -- 1 row
Table1(col1,col2....SN) - SN is forienKey -- 1 row
Table2(col1,col2,....SN) - SN is forienKey -- 1 row
Table3(col1,col2,.....regId) - regId is forienKey -- 1 row
Table4(col1,col2,.....regId) - regId is forienKey - 2 rows
Table5(col1,col2,.....regId) - regId is forienKey - 2 rows
Table6(col1,col2,.....regId) - regId is forienKey - 1 row
There is a one to many mapping
between the main table
and table 4
and table 5
.
I have tried using inner join to fetch the rows but I am getting duplicate values. Below is the query that I have written. Is there anything I am missing?
select * from MainTable
inner join Table1 on MainTable.SN = Table1.SN
inner join Table2 on MainTable.SN = Table2.SN
inner join Table3 on MainTable.regId = TABLE3.regId
inner join TABLE4 on MainTable.regId = Table4.regId
inner join TABLE5 on MainTable.regId = Table5.regId
inner join TABLE6 on MainTable.regId = Table6.regId
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `TABLE3` ADD INDEX `table3_idx_regid` (`regId`);
ALTER TABLE `Table1` ADD INDEX `table1_idx_sn` (`SN`);
ALTER TABLE `Table2` ADD INDEX `table2_idx_sn` (`SN`);
ALTER TABLE `Table4` ADD INDEX `table4_idx_regid` (`regId`);
ALTER TABLE `Table5` ADD INDEX `table5_idx_regid` (`regId`);
ALTER TABLE `Table6` ADD INDEX `table6_idx_regid` (`regId`);
SELECT
*
FROM
MainTable
INNER JOIN
Table1
ON MainTable.SN = Table1.SN
INNER JOIN
Table2
ON MainTable.SN = Table2.SN
INNER JOIN
Table3
ON MainTable.regId = TABLE3.regId
INNER JOIN
TABLE4
ON MainTable.regId = Table4.regId
INNER JOIN
TABLE5
ON MainTable.regId = Table5.regId
INNER JOIN
TABLE6
ON MainTable.regId = Table6.regId