我在使MySql查询生效时遇到问题。基本上我们有表: “item”(带产品) “flags”(我们使用这些来标记旗帜特定产品) “itemflagassign”(表示哪些项目有哪些标志) “客户”和“ “customerorderpos”(订购商品)。
现在我创建了这个查询,它完美地显示了每个标志的总销售额:
SELECT t4.flagid,
t4.name,
COUNT(*) AS count_totalorders,
SUM(t1.quantity_ordered - t1.quantity_cancelled) AS quantity_ordered,
SUM(t1.itemtotal) AS item_total,
SUM(t1.itemtotal - (quantity_ordered * t1.purchase_price)) AS item_earningstotal,
((SUM(t1.itemtotal) / SUM(quantity_ordered * t1.purchase_price)) * 100) AS item_calculationtotal
FROM customerorderpos t1, customerorder t2, itemflagassign t3, flag t4
WHERE t2.customerorderid=t1.customerorderid and t2.datetime >= 1388534400 and t2.status_cancelled = 0 and t3.itemid=t1.itemid and t4.flagid=t3.flagid
GROUP BY t4.flagid
但我想要包含没有销售的标志。这意味着它们存在于flag和itemflagassign表中,但在customerorder或customerorderpos中没有相应的记录。 因此,我需要 在指定日期范围内的客户订单或根本没有客户订单记录的记录。 我已经尝试了一整天用左连接重写,但查询最终会永远运行(这些是大表,订单有100000多条记录)。
有什么想法吗? 谢谢你的帮助!
答案 0 :(得分:0)
select YourColumns ...
from itemflagassign t3
inner join flag t4 on t4.flagid = t3.flagid
left join customerorderpos t1 on t3.itemid = t1.itemid
left join customerorder t2 on t2.customerorderid = t1.customerorderid
and t2.datetime >= 1388534400
and t2.status_cancelled = 0
group by ...
答案 1 :(得分:0)
解决了! 我尝试过的每个连接都让查询永远运行...虽然在LEFT JOIN中放置了一个嵌套的SELECT,但是完美无缺:
SELECT t2.flagid,
t2.name,
COUNT(distinct t3.customerorderid) AS count_totalorders,
SUM(t3.quantity_ordered - t3.quantity_cancelled) AS quantity_ordered,
SUM(t3.itemtotal) AS item_total,
SUM(t3.itemtotal - (quantity_ordered * t3.purchase_price)) AS item_earningstotal,
((SUM(t3.itemtotal) / SUM(quantity_ordered * t3.purchase_price)) * 100) AS item_calculationtotal
FROM itemflagassign t1
JOIN flag t2 on t2.flagid=t1.flagid
LEFT JOIN (select tt2.customerorderid, itemid, quantity_ordered, quantity_cancelled, itemtotal, purchase_price from customerorderpos tt1, customerorder tt2 where tt1.customerorderid=tt2.customerorderid and tt2.datetime >= MY_DATE_FROM and tt2.datetime <= MY_DATE_TO and tt2.status_cancelled = 0) t3 on t3.itemid=t1.itemid
GROUP BY t2.flagid