[英]SQL query with three tables and PHP
我在數據庫中有三個表
id | oid | product
1 | 11 | product1
2 | 12 | product2
id | column3 | column2
1 | qty | 1
1 | xyz | value
1 | xyz | value
1 | xyz | value
1 | xyz | value
2 | qty | 2
2 | xyz | value
2 | xyz | value
2 | xyz | value
2 | xyz | value
oid | column3 | column4
11 | name | krati
11 | phone | 1111
11 | xyz | value
11 | xyz | value
12 | name | JB
12 | phone | 2222
12 | xyz | value
12 | xyz | value
$query = "SELECT a.id, a.product, b.column3, b.column2, c.column3, c.column4 FROM order a JOIN order_qty b ON a.id = b.id JOIN order_detail c ON a.oid = c.oid";
$sql = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($sql)) { ?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["product"]; ?></td>
<td><?php if ($row["column3"] == 'qty') { echo $row["column2"]; } ?></td>
<td><?php if ($row["column3"] == 'name') { echo $row["column4"]; } ?></td>
<td><?php if ($row["column3"] == 'phone') { echo $row["column4"]; } ?></td>
</tr>
}
我獲取了所有值,但所有值都在多行中重復,無法在單行中獲取所有值
例
1 product1
1 product1
1 product1 2
1 product1 krati
1 product1
1 product1 1111
1 product1 1 krati 1111
2 product2 2 JB 2222
第2列和第3列中存在第3列,但是值不同會造成問題
使用LEFT JOIN代替JOIN:
$query = "SELECT a.id, a.product, b.column1, b.column2, c.column3, c.column4 FROM order a LEFT JOIN order_qty b ON a.id = b.id LEFT JOIN order_detail c ON a.oid = c.oid";
嗨,您必須為此使用子查詢檢查並更新..
SELECT a.id, a.product, b.column2 as qty, (select column4 from order_detail where column3 = 'name' and oid = a.oid ) as name, (select column4 from order_detail where column3 = 'phone ' and oid = a.oid ) as phone FROM order a LEFT JOIN order_qty b ON a.id = b.id where b.column3 = 'qty'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.