[英]How to inner join two tables to get same Colum name php MySQL
我有 3 個像這樣的圖像的表:
table-1 : topic
+-------+-----------+-----------+-------------------+
| id | name | time | data |
+-------+-----------+-----------+-------------------+
| 1 | John | 1 | 214-444-1234 |
| 2 | Mary | 1 | 555-111-1234 |
| 3 | Jeff | 1 | 214-222-1234 |
| 4 | Bill | 1 | 817-333-1234 |
| 5 | Bob | 1 | 214-555-1234 |
+-------+-----------+-----------+-------------------+
table-2 : image
+-------+-----------+-----------+-------------------+
| id | name | image | data |
+-------+-----------+-----------+-------------------+
| 1 | John | png | 214-444-1234 |
| 2 | Mary | png | 555-111-1234 |
| 3 | Jeff | png | 214-222-1234 |
| 4 | Bill | png | 817-333-1234 |
| 5 | Bob | png | 214-555-1234 |
+-------+-----------+-----------+-------------------+
table-3 : others
+-------+-----------+-----------+-------------------+
| id | name | image | data |
+-------+-----------+-----------+-------------------+
| 1 | John | png | 214-444-1234 |
| 2 | Mary | png | 555-111-1234 |
| 3 | Jeff | png | 214-222-1234 |
| 4 | Bill | png | 817-333-1234 |
| 5 | Bob | png | 214-555-1234 |
+-------+-----------+-----------+-------------------+
我需要從表 1 和表 2、表 3 中獲取所有數據,但我對此有疑問。 我嘗試使用內連接或左連接,但正如您在上面的示例中看到的那樣,我在兩個表(圖像列)中有相同的名稱列,所以當我進行內連接時,我只得到一個列圖像。
如何給列(圖像)一個不同的名稱以通過內部連接獲得它?
我的代碼;
<?php
require_once 'con.php';
$id=$_GET['id'];
$sql= "SELECT * FROM topics // table-1
LEFT JOIN Image ON topics.id = Image.POSTID // table-2
LEFT JOIN Category ON topics.IDCategory = Category.idMainCat // table-3
where topics.id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
$json = json_encode(["result" => "No Data Foun"]);
}
echo $json;
$con->close();
?>
你必須用別名來做:
$sql = "SELECT topics.*, Image.id as image_id, Image.name as image_name, Image.image as image_image, Category.id as category_id, Category.name as category_name, Category.image as category_image, Category.date as category_date
FROM topics // table-1
LEFT JOIN Image ON topics.id = Image.POSTID // table-2
LEFT JOIN Category ON topics.IDCategory = Category.idMainCat // table-3
where topics.id = ?";
首先,我建議您注意MySQL 關鍵字和保留字,例如您的time
。 如果可能,它應該在反引號內或重命名。
其次, SELECT *
這絕不是一個好主意,只過濾你真正需要的列。
根據問題,您應該使用別名。 我在表名和列名上使用了別名來區分
select t.id as topic_id,
t.name as topic_name,
t.time as topic_time,
t.data as topic_data,
i.id as image_id,
i.name as image_name,
i.image as image_image,
i.data as image_data,
o.id as others_id,
o.name as others_name,
o.image as others_image,
o.data as others_data
from topic t
left join image i on t.data=i.data
left join others o on o.data=t.data
where t.id=5 ;
注意。 您可以在 JOINS 類型 INNER/LEFT 之間進行選擇,我在上面的示例中使用了 LEFT,並選擇數據作為連接列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.