如何在一个表行上组合sql JOIN结果,以便在两个表

时间:2016-09-22 19:54:50

标签: php mysql sql

我有一个表,它输出表1中的所有sql结果。它的主列(stationName)具有所有唯一的名称。我在这个新表中添加了列,还包括表2中的结果(分数)。以下查询产生的结果分布在新行中,创建了相同名称的重复项。

$query =   "SELECT * FROM table1 
            LEFT JOIN table2 ON table1.stationName = table2.stationName";

$stationsList = mysqli_query($link, $query);


<?php while($row = mysqli_fetch_array($stationsList)):;?>

<tr>
<td><?php echo $row[table1ItemA];?></td>
<td><?php echo $row[table1ItemB];?></td>
<td><?php echo $row[table1ItemC];?></td>
<td><?php echo $row[table1ItemD];?></td>
<td><?php echo $row[table2score1];?></td>
<td><?php echo $row[table2score2];?></td>
<td><?php echo $row[table2score3];?></td>
</tr>

<?php endwhile;?>

将得分列输出为:

Name A Score 1

Name A .............Score 2

Name A ............................Score 3

What I would like to achieve is:


Name A Score 1, Score 2, Score 3.

GROUP BY不起作用,因为它只返回三列的一个分数。

做一些研究,我相信我需要使用DISTINCT。

但是,我仍然需要能够从table1中选择SELECT *,或者至少能够在组合表中包含所有这些内容。

有人可以提出最好的方法吗?

修改

更好地展示两个表以及我想要实现的目标。

表1(固定信息)

+-------------+------------+---------+
| StationName |  Address   | Manager |
+-------------+------------+---------+
| Station1    | London     | John    |
| Station2    | Liverpool  | Phil    |
| Station3    | Manchester | Mike    |
+-------------+------------+---------+

表2(每月变化)

+-------------+--------+--------+--------+
| StationName | Score1 | Score2 | Score3 |
+-------------+--------+--------+--------+
| Station1    | Pass   | Fail   | Pass   |
| Station2    | Fail   | Pass   | Pass   |
| Station3    | Pass   | Pass   | 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   |
+-------------+------------+---------+--------+--------+--------+

0 个答案:

没有答案