我有一个代码,可以选择10个用户获得""由价格desc订购的钱。 我一直在使用这个查询:
SELECT products.seller,
SUM(products.price * (1 - reseller.fee / 100)),
COUNT(*)
FROM products
INNER JOIN reseller ON reseller.username = products.seller
WHERE (products.seller!= 'MYSITE')
AND products.sold=1
AND products.sellerpaid=0
AND products.username != 'None'
GROUP BY products.seller
ORDER BY SUM(products.price * (1 - reseller.fee / 100)) DESC
LIMIT 10
由此我得到:
uploaded_by SUM() COUNT()
username 10.00 2
username1 11.00 3
....
哪种方法绝对正常, 但现在我有另一张桌子,产品1 这包含了更多我不能合并它们的原因,所以我希望得到与第一个相同的结果,但也要从这个表中获取所有产品的价格。 我尝试过LEFT JOIN,RIGHT JOIN和其他许多人,但仍然无法正确完成。
请不要告诉我阅读有关加入的更多信息,因为我已经拥有,只是无法做到,如果您能提出解决方案,请尽可能发布。
如果有任何您不理解的内容,请发表评论,以便进一步解释。
答案 0 :(得分:1)
福克
如果我没错,你可以使用两个表的UNION。我不知道MySQL是否支持此功能,但SQLServer确实:
SELECT tmp.seller,
SUM(tmp.price * (1 - tmp.fee / 100)),
COUNT(*)
FROM (select p.seller, p.price, r.fee from products p
INNER JOIN reseller r ON r.username = p.seller
WHERE (p.seller!= 'MYSITE')
AND p.sold=1
AND p.sellerpaid=0
AND p.username != 'None'
UNION ALL
select p1.seller, p1.price, r1.fee from products p1
INNER JOIN reseller r1 ON r1.username = p1.seller
WHERE (p1.seller!= 'MYSITE')
AND p1.sold=1
AND p1.sellerpaid=0
AND p1.username != 'None') tmp
GROUP BY tmp.seller
ORDER BY SUM(tmp.price * (1 - tmp.fee / 100)) DESC
LIMIT 10
希望帮助你
PD。对不起,我的英文不好hehehehe
答案 1 :(得分:1)
通过玩一些查询,我设法解决了这个问题。 解决方案是:
SELECT * FROM (select p.seller, sum(p.price * (1-r.fee/100)) as sumi, count(*) as counti from products p
INNER JOIN reseller r ON r.username = p.seller
WHERE (p.seller!= 'MYSITE')
AND p.sold=1
AND p.resellerpaid=0
AND p.username != 'None'
GROUP BY p.seller
UNION
select p1.seller, sum(p1.price * (1-r1.fee/100)) as sumi, count(*) as counti from products1 p1
INNER JOIN reseller r1 ON r1.username = p1.seller
WHERE (p1.seller!= 'MYSITE')
AND p1.sold=1
AND p1.resellerpaid=0
AND p1.username != 'None' GROUP BY p1.seller) tmp
ORDER BY sumi DESC
我感谢@ gerardo-hiram-vega-cabrera对于他的回答,他的答案真的帮助我弄清楚UNION是如何工作的,在读完谷歌上发现的大量废话之后,我无法弄明白。
感谢stackoverflow;)