I am trying to fetch data from mySql DB
. Total there are 9 tables and i have to display the product list accordingly from all tables.
I thought of using JOINs and tried LEFT JOIN as below:
$query="SELECT table1.*,tbl2.*,tbl3.*,tbl4.*,tbl5.*,tbl6.*,tbl7.*",tbl8.*,tbl9.* FROM
table1
LEFT JOIN tbl2 ON table1.pid=tbl2.pid
LEFT JOIN tbl3 ON table1.pid=tbl3.pid
LEFT JOIN tbl3 ON table1.pid=tbl4.pid ... and so on upto tbl9 GROUP BY table1.pid";
Here Table1
is the main table and pid is FK
to all tables from tbl2 to tbl9.
Note: Here i have used .*
on all tables to avoid long query but in actual DB operation only particular columns are mentioned to improve performance.
Now actual problem is that i am not getting all records from tables using LEFT JOIN. Only last rows are retrieved of each entry corresponding in
table1
.
- I have used GROUP BY to avoid duplicate entries with LEFT JOIN.
Example of Data.
Suppose table1
has one product with id 2
then there are multiple entries in tbl2,tbl3 and so on.. with reference to id 2
.
How can i get all data from other tables too without having duplicate rows.
Table Structure
table1
id | name | lastName
---------------------------------------
1 | john | doe
2 | helen | keller
table2
The userID column is a foreign key that references John Doe, so John orders 3 items.
id | userID | order
---------------------------------------
1 | 1 | pizza
2 | 1 | pasta
3 | 1 | lasagna
Table3
The userID column is a foreign key that references John Doe, so John leaves 5 reviews.
id | userID | rating | comment
-------------------------------------------------
1 | 1 | 5/5 | was good
2 | 1 | 5/5 | excellent
3 | 1 | 4/5 | great
4 | 1 | 4/5 | great
5 | 1 | 4/5 | great
Table Structure is copied from HERE because it is same as mine.
Result shall be as below:
id name lastname order order1 order2 MoreDetails
-------------------------------------------------
1 John doe pizza pasta lasgana click to view
Now when person click on view then a popup is displayed with all data from table 3.
Pivot table is no needed here because Data representation is different.