[英]LARAVEL - Retrieve fields from parent table through Foreign Key on child table
[英]Retrieve Fields from Foreign key table
我有這兩個表,我想從第二個表中獲得一些值,以獲取第一個表中的兩個外鍵。
團隊表:
ID | Name | No_Players | Country | F_Year | Team_Logo
-----+---------------+------------+----------+--------+----------------------
1 | Real Madrid | 22 | Spain | 1940 | Http://Xyz.jpg
2 | Arsenal | 22 | England | 1950 | Http://XXYYZZ.jpg
3 | FCB.Barcelona | 22 | Spain | 1960 | Http://YYZZz.jpg
4 | Bayern Meunekh| 22 | Germany | 1940 | Http://GGG.jpg
匹配表:
ID | Date |First_Team | Second_Team | M_Country |M_City | M_Period | Result
------------------------------------------------------------------------------------------
1 |15-02-2016 | Real Madrid | Arsenal | Spain | Madrid | 120 | 1-1
2 |19-03-2016 | FCB.Barecolna | Madrid | Spain | Madrid | 90 | 4-5
而且我想在此PHP腳本的json表單中為matchs表中的每個團隊獲取Team_Logo。 我嘗試獲取團隊徽標,但不幸的是查詢無效。
如果有人可以幫助我嗎?
<?php
require ('config.php');
$conn = mysqli_connect($servername, $username, $password, $db);
$query = "select * from matches,team where matches.first_team=team.Name OR matches.second_team=team.Name";
$result = mysqli_query($conn, $query);
$rows = array();
echo mysqli_error($conn);
while($row = mysqli_fetch_assoc($result)) {
$rows[]=$row;
}
echo json_encode($rows);
?>
SELECT
matches.*,
t1.Team_Logo AS logo1,
t2.Team_Logo AS logo2
FROM matches
JOIN team AS t1
ON t1.Name = matches.First_Team
JOIN team As t2
ON t2.Name = matches.Second_Team
另請注意,您不應選擇*,因為團隊表中的Id列將覆蓋比賽表中的Id列。 這就是為什么您應該只包含您要選擇的列的原因。
您應該嘗試以下查詢:
$query="select m.*,t.* from matches as m INNER JOIN on team as t1 ON m.First_Team=t1.Name JOIN team As t2
ON m.Second_Team=t2.Name";
使用關系數據庫結構。
為兩個表添加主鍵
在第二個表中添加第一個表的主鍵的引用鍵作為外鍵。
並參考下面的查詢。
sql="SELECT * FROM Matches as m JOIN Team as t ON t.ID = m.t_id where t.id=1 OR t.id=2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.