Mysql子查询太慢,查询销售数量

时间:2014-11-14 15:29:04

标签: mysql subquery

我有三张桌子: 一:table order_info

ordre_id     int
add_time     int

二:table order_goods

id           int
goods_id     int
order_id     int
sale_number  int
三:表商品

goods_id     int 
goods_name   varchar

现在我想通过这个号码查询商品销售总数和订单,当商品没有销售号码时,显示为零。我使用子查询,但它太慢了,sql就像:

SELECT t.* 
FROM goods AS tg 
LEFT JOIN (
    SELECT SUM(og.goods_number) AS total_num, g.goods_id, g.goods_name 
    FROM order_info oi 
    LEFT JOIN order_goods AS og     ON oi.order_id=og.order_id 
    LEFT JOIN goods AS g            ON g.goods_id=og.goods_id 
    WHERE oi.add_time>1415635200 
) AS t          ON t.goods_id=tg.goods_id 
ORDER BY t.total_num DESC;

你能有一些商品吗?谢谢!

3 个答案:

答案 0 :(得分:0)

为什么不删除外部查询部分并运行

select 
    SUM(og.goods_number) AS total_num, 
    g.goods_id, 
    g.goods_name 
from 
    order_info oi 
left join order_goods AS og on oi.order_id=og.order_id 
left join goods AS g on g.goods_id=og.goods_id 
right join goods as g2 on g2.goods_id=og.goods_id 
where  oi.add_time > 1415635200 

? 您在桌子上设置了哪些指数?

答案 1 :(得分:0)

您不需要外部查询 您可以改用GROUP BY

select SUM(og.goods_number) AS total_num, 
       g.goods_id, 
       g.goods_name
from order_info oi 
left join order_goods AS og 
on oi.order_id=og.order_id 
left join goods AS g 
on g.goods_id=og.goods_id 
where  oi.add_time>1415635200 
group by g.goods_id, g.goods_name
order by total_num desc

答案 2 :(得分:0)

如果我读了你的问题,你需要全部销售所有商品。 试试这个:

Select  g.goods_id, g.goods_name, IsNull(SUM(og.goods_number), 0) as total_num
From goods g
Left Join order_goods og
    On og.goods_id = g.goods_id
Left Join order_info oi
    On oi.order_id = og.order_id
WHERE oi.add_time>1415635200
Group By g.goods_id, g.goods_name
Order By total_num desc

我实际上只是对你的查询感到困惑。 " goods_number"专栏来自哪里? 是什么意思" sale_number"专栏?