[英]How to select data from one table and get all associated records from another table?
[英]Select all records from table 1 then select all records from table 2 matching table 1 primary key
我有兩個表,第一個表有一個主鍵 c_id。 第二個表有自己的主鍵和外鍵 c_id(表 2 可以有多個與表 1 相關的條目)
我嘗試查詢第一個表中的所有記錄,但也查找與主鍵匹配的第二個表中的所有記錄,並將其列之一回顯到查詢中的一列。
這是我的代碼注意:我是連接表的新手,因此以下代碼只是回顯表 1 中的記錄。
<?php
include_once('connected.php');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM files ORDER BY c_id Desc";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Total = %d \n",$rowcount);
// Free result set
mysqli_free_result($result);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td> <b>". $row["c_no"]." </b>
<td> <b>". $row["c_applicants"]. " </b> //this rows should echo all records from 2nd table
<td> <b>". $row["c_details"]. " </b>
<td> <b>". $row["c_for"]. " </b>
<td> <b>". $row["c_person"]. " </b>
<td> <b>". $row["c_country"]. "</b>
<td> <b>". $row["c_rdate"]. " </b>
<td> <b>". $row["c_galdate"]. "</b>
<td> "."<a href=viewfile.php?id=". $row['c_id'] .">Expand</a>". "<br>";
}
} else {
echo " results";
}
$conn->close();
?>
您應該能夠從表 1 -> 表 2 編寫連接查詢。
這是初學者的好資源
作為起點,這里有一個查詢,您可能需要對其進行調整,但會將您導向正確的方向。
select columns, you, actually, want from table1 as t1
join table2 as t2
on t1.id = t2.other_id
order by t1.id desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.