[英]Query to fetch multiple data by joining multiple tables using PHP and MySQL
我需要一個幫助。使用PHP和Mysql加入多表后,我需要獲取一些數據,因此我需要對此進行適當的查詢。我在下面解釋我的表結構。
db_order:
id order_id promocode
1 10 A12016
2 11 A12016
db_order_product:
id order_id pro_data_id quantity
1 10 20 2
2 10 22 3
3 11 20 1
db_product_info:
pro_data_id product_name
20 abc
22 xyz
我已經嘗試過類似下面的方法,但是它不起作用。
$sqlqry="select * from db_order order by id desc";
$orderqry=mysqli_query($con,$sqlqry);
while($row=mysqli_fetch_assoc($orderqry)){
$order_id=$row['order_id'];
$sqlproqry="select * from db_order_products where order_id='".$order_id."'";
$proqry=mysqli_query($con,$sqlproqry);
while($row1=mysqli_fetch_assoc($proqry)){
$product_data_id=$row1['pro_data_id'];
$sqldataqry="select * from db_product_data where pro_data_id='".$product_data_id."'";
$prodataqry=mysqli_query($con,$sqldataqry);
while($prodatarow=mysqli_fetch_assoc($prodataqry)){
$pro_id=$prodatarow['pro_Id'];
$sqlpro="select * from db_product_info where pro_Id='".$pro_id."'";
$prodata=mysqli_query($con,$sqlpro);
$prorow=mysqli_fetch_array($prodata);
}
}
$result[]=array('id'=>$row['id'],'order_id'=>$row['order_id'],'promocode'=>$row['promocode'],'order_pro_id'=>$row1['id'],'pro_data_id'=>$row1['pro_data_id'],'pro_quantity'=>$row1['quantity'],'product_name'=>$prorow['Product_name']);
}
echo json_encode($result);
在這里我需要第一個用戶進入db_order
表以獲取所有值,並根據order_id
從db_order_product
獲取所有數據,然后根據db_order_product
表中的pro_data_id
從db_order_product
中獲取數據,並db_product_info
返回db_product_info
中的所有數據。請幫助我。
只需使用一個簡單的JOIN
SELECT o.id, o.order_id, o.promocode, p.id AS order_pro_id, p.prod_data_id, p.quantity AS pro_quantity, i.product_name
FROM db_order AS o
JOIN db_order_products AS p ON o.order_id = p.order_id
JOIN db_product_data AS d ON p.pro_data_id = d.pro_data_id
JOIN db_product_info AS i ON i.pro_Id = d.pro_Id
ORDER BY o.id DESC
您必須解決您的查詢:
使用以下查詢:
select * from db_order,db_order_product,db_product_info where db_order.order_id=db_order_product.order_id and db_order_product.pro_data_id=db_product_info.pro_data_id
SELECT dor.id,dordor.order_id,dor.promocode
FROM db_order AS dor
JOIN db_order_product AS dop ON dop.order_id = dor.order_id
JOIN db_product_info as dpi ON dpi.pro_data_id=dop.pro_data_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.