我有一个问题,我无法弄清楚如何从表格中获得所有订单。 这是我的桌子
订单:
def multiply(a, b):
c = int(a) * int(b)
return c
order_item:
| order_id | user_id |
----------------------
| 3 | 1 |
----------------------
| 5 | 2 |
----------------------
| 7 | 4 |
项目:
| item_order_id | order_id | item_id |
--------------------------------------
| 1 | 3 | 1 |
--------------------------------------
| 2 | 3 | 2 |
--------------------------------------
| 3 | 5 | 1 |
如表1所示,订单可以有多个项目订单,例如示例ID 3已订购了item1和item2。
我的目标是在我的网页上的表格中显示所有订单,它应该看起来像这样:
| item_id | item_name | price |
-----------------------------------
| 1 | item1 | 100 |
-----------------------------------
| 2 | item2 | 250 |
-----------------------------------
| 3 | item3 | 150 |
这是我的php代码:
| order id | orders | price | user_id |
----------------------------------------------------
| 3 | item1,item2 | 350 | 1 |
----------------------------------------------------
| 5 | item2 | 250 | 2 |
----------------------------------------------------
| 7 | item3 | 150 | 4 |
问题是,当我的$sql = "SELECT MAX(order_id) FROM orders";
$res = mysqli_query($conn,$sql);
$result = mysqli_fetch_assoc($res);
$count = $result['MAX(order_id)'];
for($i = 1;$i<$count;$i++){
$sql = "SELECT o.order_id, u.username, i.item_name FROM orders o
JOIN order_item oi ON oi.order_id=o.order_id
JOIN users u on u.user_id=o.user_id
JOIN item i ON i.item_id=oi.item_id WHERE o.order_id = $i";
$res = mysqli_query($conn,$sql);
while ($result = mysqli_fetch_assoc($res)){
$order_id = $result['order_id'];
$item = $result['item_name'];
$username = $result['username'];
echo "<td style='border-top:1px solid #5C1916;'>$order_id </td>
<td style='border-top:1px solid #5C1916;'>$item </td>
<td style='border-top:1px solid #5C1916;'> $username </td>
</tr>" ;
}}
说3时,该用户有2个订购商品,并且将这些商品显示在两个单独的行中,我希望它就像上面的表格一样。任何人都知道吗我该如何实现?
答案 0 :(得分:1)
在您的示例中,订单ID = 1的不是order_ite
因此,如果您只需要匹配行,则使用内部联接
select a.order_id , group_concat(c.item_name), sum( c.price), a.user_id
from orders a
inner join order_item b on a.order_id = b.order_id
inner join item c on c.item_id = b.item_id
group by a.order_id
否则使用左联接
select a.order_id , group_concat(c.item_name), sum( c.price), a.user_id
from orders a
left join order_item b on a.order_id = b.order_id
inner join item c on c.item_id = b.item_id
group by a.order_id