MySQL:如何将2个MySQL表中的数据连接到1个单独的HTML表

时间:2017-05-30 22:59:34

标签: mysql

我有两个基本上采用以下格式的MySQL表:

表1

id  |  screeningId  |  mainImageUrl  |  movie  |  venue  |  location  |  date

 1          1            red.jpg       Movie1     Venue1    Location1    2015
 2          2            blue.jpg      Movie2     Venue2    Location2    2016
 3          3            orange.jpg    Movie3     Venue3    Location3    2016
 4          4            white.jpg     Movie4     Venue4    Location4    2017

表2

id | screeningId | imageUrl
 1        1        red2.jpg
 2        1        red3.jpg
 3        1        red4.jpg
 4        2        red5.jpg
 5        2        red6.jpg
 6        3        red7.jpg
 7        4        blue2.jpg
 8        4        blue3.jpg
....
....

我想将此数据打印到HTML表格中,格式如下:

id |    venue    | imageUrl
 1      venue1     red2.jpg
 2      venue1     red3.jpg
 3      venue1     red4.jpg
 4      venue2     red5.jpg
 5      venue2     red6.jpg
 6      venue3     red7.jpg
 7      venue4     blue2.jpg
 8      venue4     blue3.jpg
....
....

对于第二个表,这是我将其打印到HTML表格的代码:

<table border=1 cellpadding=1 cellspacing=1>
            <thead>
                <tr>
                    <th>Screening Event</th>
                    <th>Secondary Image</th>
                </tr>
            </thead>
            <?php

                //select query
                $sql = "SELECT * FROM table2";
                if(!$sql){
                    echo"Table not selected";
                }

                //execute the query
                $records = mysqli_query($db, $sql);

                while ($row = mysqli_fetch_array($records)){
                    echo "<tr>";
                    echo "<td>".$row['screeningId']."</td>";
                    echo "<td>".$row['imageURL']."</td>";
                    echo "</tr>";
                }
            ?>
        </table>

当然,这只是输出screeningId而不是表1中该筛选的匹配场所。如何更改呢?

1 个答案:

答案 0 :(得分:1)

您希望将查询编写为连接,然后打印出连接的所有行。您想要的查询是:

select T1.id as id, T1.venue as venue, T2.imageUrl as imageUrl 
from table1 T1 join table2 T2 on T1.screeningId = T2.screeningId;

然后,您可以通过$row['id']$row['venue']$row['imageUrl']将每行的字段输出为HTML。