我的查询是(在此查询中我们得到冗余结果错误的值)
SELECT
ggk_user.user_id,
ggk_user.user_email,
SUM(ggk_shop_item.item_price) as total_amount,
SUM(ggk_userpayment.up_amount) as paid
FROM ggk_user
LEFT JOIN ggk_product ON ggk_user.user_id = ggk_product.product_user_id
LEFT JOIN ggk_shop_item ON ggk_product.product_id = ggk_shop_item.item_product_id
INNER JOIN ggk_userpayment ON ggk_user.user_id = ggk_userpayment.up_user_id
WHERE ggk_user.user_type = 1
AND ggk_user.user_status = 1
GROUP BY ggk_user.user_id,ggk_userpayment.up_user_id
如果运行此查询。
SELECT
ggk_user.user_id,
ggk_user.user_email,
SUM(ggk_shop_item.item_price) as total_amount
FROM ggk_user
LEFT JOIN ggk_product ON ggk_user.user_id = ggk_product.product_user_id
LEFT JOIN ggk_shop_item ON ggk_product.product_id = ggk_shop_item.item_product_id
WHERE ggk_user.user_type = 1
AND ggk_user.user_status = 1
GROUP BY ggk_user.user_id,ggk_userpayment.up_user_id
此查询工作正常,因此第3次加入的问题是由于第3次加入用户ID等于用户表用户ID所以如何修复此错误?
答案 0 :(得分:1)
使用内联视图从GGK_USERpayment生成付费金额,因此表格之间的基数不会影响其他金额。
如下所示;但我们可能还需要为total_amount生成内联视图。我不太清楚表格之间的关系,知道是否需要它。
SELECT ggk_user.user_id
, ggk_user.user_email
, SUM(ggk_shop_item.item_price) as total_amount
, ggk_userpayment.paid
FROM ggk_user
INNER JOIN (SELECT sum(up_Amount) as Paid, up_user_ID
FROM ggk_userpayment
GROUP BY up_user_ID ) ggk_userpayment
ON ggk_user.user_id = ggk_userpayment.up_user_id
LEFT JOIN ggk_product
ON ggk_user.user_id = ggk_product.product_user_id
LEFT JOIN ggk_shop_item
ON ggk_product.product_id = ggk_shop_item.item_product_id
WHERE ggk_user.user_type = 1
AND ggk_user.user_status = 1
GROUP BY ggk_user.user_id
, ggk_userpayment.up_user_id