我正在尝试使用单个查询从数据库中获取所有产品。我陷入了价格部分:
VirtueMart有一个名为#__vm_product的表,另一个名为#__ vm_product_price。
如果产品有父产品,则意味着产品继承了父产品中的所有产品,除非在产品中设置不同。
表格如下:
/* #__vm_product PARTIAL */
int - product_id
int - product_parent_id
varchar - product_name
/* #__vm_product_price PARTIAL */
int - product_id
decimal - product_price
int - mdate
我制作了下一个查询,其中包含所有产品的价格:
SELECT
p.product_id AS id,
product_name AS name,
product_price AS price,
p.product_parent_id AS parent,
MAX(pp.mdate) AS last_updated
FROM jos_vm_product p
LEFT JOIN jos_vm_product_price pp ON p.product_id = pp.product_id
GROUP BY p.product_id
ORDER BY p.product_id
此查询的问题在于它不会检查它们是否是指定的价格。因此,如果它是儿童产品并且没有价格,它应该显示它的父母的价格。
有人可以帮我解决这个问题吗?
注意:如果有人知道从VirtueMart数据库获取所有产品(有价格)的更简单方法,请不要告诉我:)
编辑:价格永远不会为空。如果孩子应该继承它的父母,那么它在jos_vm_product_price中没有价格行
答案 0 :(得分:1)
您可以使用CASE
语句检查子级的产品价格,如果为null,则使用父级价格。
此外,您需要另一个联接才能获得父级。
SELECT
p.product_id AS id,
product_name AS name,
CASE
WHEN pp.product_price IS NULL then pp2.product_price
ELSE pp.product_price
END AS price,
p.product_parent_id AS parent,
MAX(pp.mdate) AS last_updated
FROM jos_vm_product p
LEFT OUTER JOIN jos_vm_product_price pp
ON p.product_id = pp.product_id
, jos_vm_product parent
, jos_vm_product_price pp2
WHERE (p.product_parent_id = parent.product_id OR p.product_parent_id IS NULL)
AND (parent.product_id = pp2.product_id OR p.product_parent_id IS NULL)
GROUP BY
p.product_id,
product_name,
CASE
WHEN pp.product_price IS NULL then pp2.product_price
ELSE pp.product_price
END,
p.product_parent_id
答案 1 :(得分:1)
<强>更新强>
select
p.product_id AS id,
p.product_name AS name,
coalesce(pp.product_price, pp2.product_price) AS price,
p.product_parent_id AS parent,
coalesce(pp.mdate, pp2.mdate) AS last_updated
from jos_vm_product p
left outer join jos_vm_product p2 on p.product_parent_id = p2.product_id
left outer join (
select product_id, max(mdate) as maxmdate
from jos_vm_product_price
group by product_id
) ppm on p.product_id = ppm.product_id
left outer join jos_vm_product_price pp on ppm.product_id = pp.product_id and ppm.maxmdate = pp.mdate
left outer join (
select product_id, max(mdate) as maxmdate
from jos_vm_product_price
group by product_id
) ppm2 on p2.product_id = ppm2.product_id
left outer join jos_vm_product_price pp2 on ppm2.product_id = pp2.product_id and ppm2.maxmdate = pp2.mdate