【发布时间】:2017-04-07 07:42:09
【问题描述】:
如何在 php 中将这 3 个表合并到一个查询中?当我使用这个查询时,我从匹配和运动中获取值为空。但是当我将最后一个右连接更改为左连接时,schedule 的值变为空。我怎样才能解决这个问题?谢谢。
PHP
<?php
$db_name = "atfest_db";
$mysql_user = "root";
$mysql_pass = "";
$server_name = "localhost";
$sql = "SELECT teamone,teamtwo,s_name,start,end,venue FROM `sport` right JOIN `matches` ON `matches`.`s_id` = `sport`.`s_id` right JOIN `schedule` ON `schedule`.`m_id` = `matches`.`m_id`";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
$result = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("teamone"=>$row[0], "teamtwo"=>$row[1],
"s_name"=>$row[2]));
}
echo json_encode (array("schedule_response"=>$response));
mysqli_close($con);
?>
运动表连接到比赛 b s_id,而比赛表通过 m_id 连接到日程表。
这是我得到的输出
{"schedule_response":[{"start":null,"end":null,"venue":null,"teamone":
"hehe","teamtwo":"haha","s_name":"Soccer"}
我需要的是从时间表表中获取值的开始、结束和地点。像这样的
{"schedule_response":[{"start":2016-11-30 00:00:00,"end":2016-12-01
00:00:00,"venue":aaaaaa,"teamone":"hehe","teamtwo":"haha","s_name":"Soccer"},
【问题讨论】:
-
正确加入?人还在用这个?要么使用
INNER JOIN只匹配,要么使用你的RIGHT JOIN当右(在位置)表是前导表时。 -
你的主表是什么?运动或时间表或比赛?哪个表是主表?
-
正确的 JOIN 非常罕见。只是说';-)
-
因为matches.m_id和schedule.m_id没有关系,所以schedule的值会为null
-
Matches.m_id 表示 150 和 151,而 schedule.m_id 表示 null 和 null。尝试将 schedule.m_id 中的 NULL 和 NULL 替换为 150 和 151,然后检查结果。