[英]How to print for each primary key all the foreign keys column related to it?
我想解決 PHP 問題
我有一個帶有 2 個表的數據庫:第一個是“文檔”:
id | title | ================================ 1 | equations | 2 | great | 3 | painting |
第二個是“圖片”:
id | doc_id | description
===============================================
1 | 1 | "mathematics"
2 | 1 | "physic"
3 | 2 | "literature"
4 | 2 | "art"
這是我的問題:我正在嘗試為每個標題打印與之相關的所有描述,例如:
for the title "equations", the foreign key related to it, is "doc_id =1" which means for "equations" I will print "mathematics" and "physic"
在我的瀏覽器上使用 PHP 和 SQL 打印的最終表格應該是:
| title | description
===============================================
| equations | mathematics, physic
| great | literature , art
| painting |
這是我的代碼:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "doc-pic";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
$sql = "SELECT * FROM pic LEFT JOIN document ON pic.doc_id=document.id";
$result = mysqli_query($conn, $sql);
$sql1 = "SELECT title from document";
$result1 = mysqli_query($conn, $sql1);
?>
<table>
<?php
if (mysqli_num_rows($result1) > 0)
while($row = mysqli_fetch_array($result1)){?>
<tr>
<td><?php echo $row["title"]; ?></td>
</tr>
<?php if (mysqli_num_rows($result) > 0 )
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td><?php echo $row["doc_id"]; ?></td>
<td><?php echo $row["description"]; ?></td>
</td>
</tr>
</td>
<?php }
} ?>
使用left join
和聚合:
select d.*,
group_concat(p.description order by p.id) as full_description
from documents d left join
pic p
on p.doc_id = d.id
group by d.id;
請注意,這使用group by d.id
以及select d.*
。 這是有效的,因為d.id
是(大概) documents
的主鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.