使用sql内部联接从两个表中获取数据,试图获取非对象的属性

问题描述 投票:-1回答:1

我有两个表事件和会话,看起来像这样

事件表

enter image description here

会话表enter image description here

这里是预期结果

enter image description here

这是我的解决方法

  <table>
                  <tr>
                    <th>Sessions </th>
                    <th>konto</th>
                    <th>Mobile</th>
                    <th>Komputer</th>
                    <th>Date</th>
                  </tr>       
                  <?php
                      $conn = mysqli_connect("localhost", "root", "", "ideabank_julia");
                      // Check connection
                      if ($conn->connect_error) {
                      die("Connection failed: " . $conn->connect_error);
                      }
                      $sql = "SELECT sid, datetime, count(*) as num_rows, count(distinct sid) as sessions,  
                      sum( targetbuttonname = 'konto' ) as num_konto,
                      sum(devicetype ='Computer') as num_computer, 
                      sum(devicetype = 'Mobile') as num_mobile from events
                      INNER JOIN sessions ON events.sid = sessions.sid group by sid, datetime;";

                      $result = $conn->query($sql);
                      if ($result->num_rows > 0) {
                      // output data of each row
                      while($row = $result->fetch_assoc()) {
                      echo "<tr>
                      <td>". $row["num_rows"]."</td>
                      <td>". $row["num_konto"]."</td>         
                      <td>". $row["num_mobile"]. "</td>
                      <td>". $row["num_computer"]. "</td>
                      <td>". $row["datetime"]. "</td>

                      </tr>";
                      }
                      echo "</table>";
                      } else { echo "0 results"; }
                      $conn->close();
                      ?>
                </table>

不幸的是,当我在phpmyadmin上运行脚本时,出现以下错误

 # 1052 - Column: 'sid' in field list is ambiguous

并且当我在上面的php脚本上运行时,出现以下错误

Trying to get property of non-object

我的代码在做什么错?任何想法或帮助将不胜感激

php mysql sql html-table phpmyadmin
1个回答
0
投票

我认为您应该在所选列中添加别名,以提及您从哪个表中获取列。请尝试下面的代码。

© www.soinside.com 2019 - 2024. All rights reserved.