组合两个sql表的数据后,结果输出到HTML表的方式有问题。
表1如下所示
+-------------+------------+---------+
| StationName | Address | Manager |
+-------------+------------+---------+
| Station1 | London | John |
| Station2 | Liverpool | Phil |
| Station3 | Manchester | Mike |
+-------------+------------+---------+
表2如下所示
+-------------+--------+--------+--------+
| StationName | Score1 | Score2 | Score3 |
+-------------+--------+--------+--------+
| Station1 | Pass | | |
| Station1 | | Fail | |
| Station1 | | | Pass |
| Station2 | Fail | | |
| Station2 | | Pass | |
| Station2 | | | Pass |
| Station3 | Pass | | |
| Station3 | | Pass | |
| Station3 | | | Pass |
+-------------+--------+--------+--------+
我希望组合数据输出如下表所示
+-------------+------------+---------+--------+--------+--------+
| StationName | Address | Manager | Score1 | Score2 | Score3 |
+-------------+------------+---------+--------+--------+--------+
| Station1 | London | John | Pass | Fail | Pass |
| Station2 | Liverpool | Phil | Fail | Pass | Pass |
| Station3 | Manchester | Mike | Pass | Pass | Pass |
+-------------+------------+---------+--------+--------+--------+
然而它看起来像这样。
+-------------+------------+---------+--------+--------+--------+
| StationName | Address | Manager | Score1 | Score2 | Score3 |
+-------------+------------+---------+--------+--------+--------+
| Station1 | London | John | Pass | | |
| Station1 | London | John | | Fail | |
| Station1 | London | John | | | Pass |
| Station2 | Liverpool | Phil | Fail | | |
| Station2 | Liverpool | Phil | | Pass | |
| Station2 | Liverpool | Phil | | | Pass |
| Station3 | Manchester | Mike | Pass | | |
| Station3 | Manchester | Mike | | Pass | |
| Station3 | Manchester | Mike | | | Pass |
+-------------+------------+---------+--------+--------+--------+
我的查询是:
SELECT *
FROM table1
LEFT JOIN table2
ON table1.stationName = table2.stationName
我想我正在寻找一种使用类似于GROUP BY的方法,但没有它聚合数据。
有人提出了数据透视表,虽然根据我所读到的数据,它们对计算有用 - 我有兴趣将文本数据组合到多个表中的列,其中公共链接是站名。
有人可以建议如何实现这一目标吗?
答案 0 :(得分:0)
GROUP BY是要走的路。试试这个:
SELECT stationname, address, manager,
MIN(score1) as score1,
MIN(score2) as score2,
MIN(score3) as score3
FROM table1
LEFT JOIN table2
ON table1.stationName = table2.stationName
GROUP BY stationname, address, manager
答案 1 :(得分:0)
kbball的回答可能会解决您的问题。但是,良好的数据库设计消除了许多问题,并且可以使编码变得非常容易。
我认为您需要重新设计数据。 Table2应该只有一个得分列,然后是另一列,告诉你每行得分。如果你确实保留了三个得分列,那么填充该表的代码应该将所有三个得分放在同一行上。