好吧,我不知道如何给这个标题命名。
我有 2 张 table ,一张有产品,一张有商家。
某些产品可以由 2 个或更多商家销售。
产品表有一个名为“product_merchant_id”的列,其中有 1 个或多个引用,例如“1237, 38272, 3738”
ID 与“merchants”表中的“merchant_id”列中的内容相关。
商户表(商户)
mer_id | merchant_id | merchant_name
-------------------------------------
1 | 1237 | Merchant One
2 | 38272 | Merchant Two
3 | 3738 | Merchant Three
产品表(产品)
product_id | product_merchant_id | product_name
------------------------------------------------------------
1 | 1237, 38272 | Sample Product One
2 | 1237, 3738, 38272 | Sample Product Two
3 | 3728 | Sample Product Three
所以,基本上,如果我查询 Product_id 2,我希望能够从商家表中提取 2 行商家 ID 为 1237 和 38272 的行,并将它们循环到我的模板中,类似于...
<div>
<p>Merchant Name: Merchant One</p>
<p>Merchant ID: 1237</p>
</div>
<div>
<p>Merchant Name: Merchant Two</p>
<p>Merchant ID: 38272</p>
</div>
最佳答案
解决方案是更改表结构。删除 Product 表中的 product_merchant_id
列,然后创建一个名为 product_merchants
的新表,其中包含两列:product_id
和 merchant_id
。它看起来像:
product_id | merchant_id
--------------------------
1 | 1237
1 | 38272
2 | 1237
2 | 2728
2 | 38272
3 | 3738
现在,您可以使用联接来获取所需的所有信息。像这样的东西应该有效:
SELECT m.merchant_name, m.merchant_id
FROM merchants m
JOIN product_merchants mp ON m.merchant_id = mp.merchant_id
AND mp.product_id = 2
关于php - 使用数组选择 2 行或更多行(PHP、MYSQLi),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612735/