大家好,我如何在php的单个查询中组合这3个表?
PHP
<?php
$db_name = "atfest_db";
$mysql_user = "root";
$mysql_pass = "";
$server_name = "localhost";
$sql = "SELECT teamone,teamtwo,s_name FROM sport as A right join matches
as B right join schedule as C ON A.s_id = B.s_id ORDER by m_id asc";
$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
连接到计划表答案 0 :(得分:0)
您可以使用mysql中的join()连接两个或多个表,如:
select t1.col1, t2.col2
FROM table1 as t1 JOIN table2 as t2
on t1.some_col = t2.some_col // where t1, t2 have a common column on which joining is done
where condition;
答案 1 :(得分:0)
请尝试使用此SQL语句:
SELECT B.teamone,B.teamtwo,A.s_name
FROM sport A
LEFT JOIN matches B
LEFT JOIN schedule C
ON A.s_id = B.s_id
ORDER by C.m_id asc
答案 2 :(得分:0)
SELECT `schedule`.`id`, (and other relevant fields from schedule table), `matches`.`m_id`, `matches`.`teamone`, `matches`.`teamtwo`, (and other relevant fields from matches table), `sport`.`s_id`, (and other relevant fields from sport table)
FROM `sport`
RIGHT JOIN `matches` ON `matches`.`s_id` = `sport`.`s_id`
RIGHT JOIN `schedule` ON `schedule`.`m_id` = `matches`.`m_id`
ORDER BY `schedule`.`id`
上述查询将解决组合三个表的基本问题。但这是一种不好的做法。会有很多冗余数据。您只选择了三列。在那,也没有索引。你无法弄清楚每一行是如何彼此不同的。请提及查询的目的或逻辑。这样我们就可以相应地微调查询。
我已经更新了我们在查询中选择的列。现在,有一个唯一的列计划ID可以唯一标识每一行。您可以根据需要选择其他列。
答案 3 :(得分:0)
SELECT teamone,teamtwo,s_name FROM sport A. LEFT JOIN匹配B ON A.m_id = B.m_id LEFT JOIN计划C ON A.s_id = B.s_id ORDER by A.m_id asc
答案 4 :(得分:0)
嗨,这是对你的正确查询。您收到错误是因为您没有使用正确的查询..
SELECT teamone,teamtwo,s_name FROM sport as right join匹配为B ON A.s_id = B.s_id右连接时间表为C ON B.m_id = C.m_id order by B.m_id asc
现在您可以通过它来获得适当的结果。此查询是根据您的架构生成的。