0

我有一张存放购买的桌子,还有一张存放产品的桌子。

购买表中的每一行最多可以包含 9 个产品 ID(8 个可以为空)

id, foo, bar, baz, product_1_id, product_2_id, product_3_id, etc... 

现在我需要查询该购买表的所有字段,以显示在 html 页面中。

我不能只显示products id,所以需要在products表中找到对应的product_name。

SQL 查询让我很难受。

任何帮助将非常感激。

4

6 回答 6

2

要检索产品名称,我会试试这个:

SELECT t2.product_name as product_name_1, t3.product_name as product_name_2, t4.product_name as product_name_1, [...]
FROM purchases as t1
JOIN products as t2 ON(t1.product_1_id = t2.product_id)
LEFT JOIN products as t3 ON(t1.product_2_id = t3.product_id)
LEFT JOIN products as t4 ON(t1.product_3_id = t4.product_id)
[...]
WHERE t1.id = ...

但这可能会很慢,您可能想要重组您的数据库。

于 2012-07-31T13:53:14.010 回答
1

您需要加入 Products 表 9 次。但考虑归一化

select id, foo, bar, baz, p1.product_name, p2.product_name, p3.product_name, 
  etc...  
from purchases as pur
left join products as p1 on pur.product_1_id=p1.product_id
left join products as p2 on pur.product_2_id=p2.product_id
.
.
于 2012-07-31T13:53:26.673 回答
0

在sql中你可以这样使用..

 select *,PM.Product_id,P.Product_name from purchase_mst PM, product P where   
 PM.Product_id1=P.Product_id1 and PM.Product_id2=P.Product_id2 etc....
于 2012-07-31T13:54:47.390 回答
0

使用适当的规范化设计,您将拥有:product、purchase_Order 和 purchase_order_line,查询将是:

SELECT     ...
FROM       purchase_order
INNER JOIN purchase_order_line
ON         purchase_order.id = purchase_order_line.purchase_order_id
INNER JOIN product
ON         purchase_order_line.product_id = product.id
于 2012-07-31T13:57:08.660 回答
0

I think it would be easier if you had a table connecting purchases and products with two columns *product_id, purchase_id*.

But still, I guess you can try something like this :

SELECT pr1.name
 FROM purchases pur1, products pr1
WHERE pur1.product_1_id = pr1.id
UNION ALL
SELECT pr2.name
 FROM purchases pur2, products pr2
WHERE pur2.product_1_id = pr2.id
UNION ALL
-- and so on until
SELECT pr9.name
 FROM purchases pur9, products pr9
WHERE pur9.product_9_id = pr9.id

Although this looks pretty scary and I would strongly suggest rethinking your database design.

于 2012-07-31T14:02:22.567 回答
0

You could do this

Select purchase., product. from purchase join product on id1=id, id2=id... Etc.

Read this:

MySQL how to join tables on two fields

于 2012-07-31T14:03:17.477 回答