我有这样的表:
表格产品
[Id |姓名]
表格图片
[Product_Id |网址| ORDERNUMBER]
表格价格
[Product_Id |组合|货币|价]
表格数量
[Product_Id |组合|数量]
表产品与其他表一对多关系。我需要查询表并得到类似这样的结果(伪数组):
[
ProductId: 1,
Name: 'Sample product',
Images: [
[url, 1],
[url, 2]
],
Prices: [
[aaa, USD, 50.00],
[aaa, EUR, 50.00],
[bbb, USD, 59.00],
[bbb, EUR, 59.00]
],
Quantities: [
[aaa, 5],
[bbb, 3]
]
]
我现在的方式如下:
我查询所有产品,列出他们的ID,然后使用WHERE IN
子句查询每个表(图像,价格,数量)。当我拥有所有数据时,我开始在php中解析表以获得所需的结构。
我想知道是否有更好的方法来提取这些数据,我有很多不同的表,并为每个表创建配置解析器有点混乱和有问题。是否有可能mysql会给我带来一些负担?
谢谢
答案 0 :(得分:4)
此查询将为您解决问题:
SELECT product.id, product.name,
(SELECT group_concat(CONCAT('["',images.url, '",', images.order_number,']')) FROM images WHERE images.product_id = product.id GROUP BY (product.id)) AS IMAGES_LIST,
(SELECT GROUP_CONCAT(CONCAT('["',prices.combination, '","', prices.currency, '",', prices.price,"]" )) FROM prices WHERE prices.product_id = product.id GROUP BY (product.id)) AS PRICE_LIST,
(SELECT GROUP_CONCAT(CONCAT('["',quantites.combination, '",', quantites.quantity,"]")) FROM quantites WHERE quantites.product_id = product.id GROUP BY (product.id)) AS Quantity_LIST
FROM product WHERE product.id = 1
答案 1 :(得分:0)
使用JOIN
比WHERE ... IN ...
更简单(如果设置了外键,效率更高)。
可以单独查询表格以获取Product Id = 1
所需的数据,如下所示:
SELECT i.*
FROM Product prd
INNER JOIN Images i
ON prd.Id = i.Product_Id
WHERE Product_Id = 1;
SELECT prc.*
FROM Product prd
INNER JOIN Prices prc
ON prd.Id = prc.Product_Id
WHERE Product_Id = 1;
SELECT q.*
FROM Product prd
INNER JOIN Quantities q
ON prd.Id = q.Product_Id
WHERE Product_Id = 1;
答案 2 :(得分:0)
我建议你有一个包含ProductID所有这些信息的结果集,并用PHP解析它。它会使事情变得更简单。
SELECT prd.ProductId, prd.Name, i.Url, i.Ordernumber, prc.Combination, prc.Currency, prc.Price,q.Combination, q.Quantity
FROM Product prd
INNER JOIN Images i
ON prd.Id = i.Product_Id
INNER JOIN Prices prc
ON prd.Id = prc.Product_Id
INNER JOIN Quantities q
ON prd.Id = q.Product_Id
WHERE Product_Id = 1;