gpt4 book ai didi

php - 加入一些行不同的 mySQL 表

转载 作者:行者123 更新时间:2023-11-29 00:07:17 24 4
gpt4 key购买 nike

我在 mySQL 数据库中有 2 个不同的表,它们的结构如下:

table_cart:

cart_id | item_id | quantity
----------------------------
00001 285 1
00002 482 2
00003 683 6
00004 627 1

table_products:

product_id | product_name | quantity
-------------------------------------------
285 some name 50
482 another name 40
683 one more name 35
627 yet another name 80

我要显示的是 table_cart 中的 2 个东西(item_id 和数量)和 table_products 中的 1 个东西(名称)。问题是,当它用我的代码抓取数量时,它从 table_products 中选择了一个,这不是我需要的那个。我想我在连接表格时做错了什么,但我尝试了 INNER、LEFT、RIGHT 等,但都没有用。

我的查询是这样的:

$product_rows = $this->query("
SELECT * FROM table_cart INNER JOIN table_products
ON table_cart.item_id=table_products.product_id
WHERE cart_id='".$cart_id."'"
");

然后我输出如下:

$item_details = mysql_fetch_array($product_rows);

$item_details['item_id']
$item_details['name']
$item_details['quantity']

我做错了什么?

最佳答案

您的 join 没问题。问题是 select * 以及两个列具有相同名称的事实(quantity 在两个表中)。

您应该明确列出您想要的列:

SELECT c.item_id, p.name, p.quantity
FROM table_cart c INNER JOIN
table_products p
ON c.item_id = p.product_id
WHERE cart_id='".$cart_id."'";

关于php - 加入一些行不同的 mySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26953742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com