我正在尝试从 mySql DB
获取数据。总共有 9 个表,我必须相应地显示所有表中的产品列表。
我想到了使用 JOIN 并尝试了 LEFT JOIN,如下所示:
$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";
这里 Table1
是主表,pid 是从 tbl2 到 tbl9 的所有表的 FK
。
注意:这里我在所有表上使用了.*
以避免长查询,但在实际的数据库操作中只提到特定的列以提高性能。
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
.
- 我使用 GROUP BY 来避免与 LEFT JOIN 的重复条目。
数据示例。
假设 table1
有一个 ID 为 2
的产品,然后在 tbl2、tbl3 等中有多个条目..引用 id 2
.
如何在没有重复行的情况下也从其他表中获取所有数据。
表结构
表 1
id | name | lastName
---------------------------------------
1 | john | doe
2 | helen | keller
表2
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
表 3
userID 列是引用 John Doe 的外键,因此 John 留下了 5 条评论。
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
表结构复制自HERE因为它和我的一样。
结果如下:
id name lastname order order1 order2 MoreDetails
-------------------------------------------------
1 John doe pizza pasta lasgana click to view
现在,当人们点击 View 时,会显示一个弹出窗口,其中包含表 3 中的所有数据。
这里不需要数据透视表,因为数据表示不同。
最佳答案
数据库: Postgresql
试试这个:
SELECT t1.id, t1.name, t1.lastname, (array_agg(t2.order))[1] as order,
(array_agg(t2.order))[2] as order1, (array_agg(t2.order))[3] as order2,
'Clicks to view' as "Moredetails"
FROM table1 as t1
LEFT JOIN table2 as t2 ON t1.id = t2."userID"
LEFT JOIN table3 as t3 ON t1.id = t3."userID"
WHERE t1.id = 1
GROUP BY 1,2,3
输出:
id name lastname order order1 order2 MoreDetails
-------------------------------------------------
1 John doe pizza pasta lasgana click to view
关于php - mySQL select查询,从多个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34940210/