[英]get data from two tables using sql inner join, Trying to get property of non-object
I have two table events and session which looks like this我有两个表事件和 session 看起来像这样
Events table事件表
Here is expected results这是预期的结果
Here is my solution这是我的解决方案
<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>
Unfortunately when i run the script on phpmyadmin I am getting the following error不幸的是,当我在 phpmyadmin 上运行脚本时,我收到以下错误
# 1052 - Column: 'sid' in field list is ambiguous
And when I run on php script above I get the following error当我在上面的 php 脚本上运行时,我收到以下错误
Trying to get property of non-object
What am I doing wrong in my code?我在我的代码中做错了什么?
I think you should add alias to your selected columns to mention from which table you are taking the colums.我认为您应该为您选择的列添加别名,以提及您从哪个表中获取列。 Please Try the code below.请尝试以下代码。
$sql = "SELECT events.sid, events.datetime, count(events.*) as num_rows, count(distinct events.sid) as sessions,
sum( events.targetbuttonname = 'konto' ) as num_konto,
sum(events.devicetype ='Computer') as num_computer,
sum(events.devicetype = 'Mobile') as num_mobile from events
INNER JOIN sessions ON events.sid = sessions.sid group by sid, datetime";
You should add alias name for coloumns in groupby condition.您应该在 groupby 条件下为列添加别名。
$sql = "SELECT even.sid, even.datetime, count(*) as num_rows,
count(distinct even.sid) as sessions,
sum( even.targetbuttonname = 'konto' ) as num_konto,
sum(devicetype ='Computer') as num_computer,
sum(devicetype = 'Mobile') as num_mobile from events even
INNER JOIN sessions ON even.sid = sessions.sid group by even.sid,
even.datetime";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.