http://blog.sina.com.cn/s/blog_5b6cb950010116om.html
- 建表
cat_id
create table if not exists cate(cat_id int(11) not null auto_increment primary key,
cat_name varchar(11) character set utf8 collate utf8_bin not null);
goods
create table if not exists goods(
goods_id int(11) not null auto_increment primary key,
goods_name varchar(11) character set utf8 collate utf8_bin not null,
cat_id int(11) not null);
order_goods
CREATE TABLE IF NOT EXISTS order_goods(
order_goods_id int(11) NOT NULL AUTO_INCREMENT primary key,
order_id int(11) NOT NULL,
goods_id int(11) NOT NULL,
goods_num int(11) NOT NULL);
order_info
CREATE TABLE IF NOT EXISTS order_info(
order_info_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
test2 varchar(11) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL);
- 插入数据
insert into cate (cat_id, cat_name) values
(1, '分类1'),
(2, '分类2');
insert into goods values
(2, '书', 1),
(3, '手机', 2),
(4, '水壶', 1),
(5, '没人买', 2);
insert into order_goods values
(1, 2, 2, 3),
(2, 2, 3, 2),
(3, 3, 4, 1),
(4, 3, 4, 1),
(5, 4, 4, 4);
INSERT INTO order_info VALUES
(2, '测试1'),
(3, '测试2'),
(4, '测试3');
- 题意----根据订单商品表(order_goods)列出商品(goods)卖的数量
逻辑是----先合并,再根据合并后的表进行groupby,进行sum
select g.goods_name, ifnull(sum(og.goods_num),0) as sell_num
from goods as g
left join order_goods as og on g.goods_id = og.goods_id
group by g.goods_id
- 根据订单商品表(order_goods)列出商品卖的数量,且列出该类别
select g.goods_name, c.cat_name, ifnull(sum(og.goods_num),0) as sell_num
from goods as g
left join order_goods as og on g.goods_id = og.goods_id
left join cate as c on c.cat_id = g.cat_id
group by g.goods_id;
- 根据订单商品表(order_goods)、指定类别ID(cat_id =1),列出商品卖的数量,且列出该类别
group by 必须在where语句后
select g.goods_name, c.cat_name, ifnull(sum(og.goods_num),0) as sell_num
from goods as g
left join order_goods as og on g.goods_id = og.goods_id
left join cate as c on c.cat_id = g.cat_id
where c.cat_id = 1
group by g.goods_id;
6.最后的
select g.*, c.cat_name,
sum(
case when(oi.order_status='7' or oi.order_status='5')
and(oi.pay_status='2')
and(oi.shipping_status='2' or oi.shipping_status='1')
then og.goods_number
else o end) as sell_num
FROM `tdm_goods` AS g
LEFT JOIN `tdm_category` AS c ON g.cat_id = c.cat_id
LEFT JOIN `tdm_order_goods` AS og ON g.goods_id = og.goods_id
LEFT JOIN `tdm_order_info` AS oi ON oi.order_id = og.order_id)
where 1
AND g.brand_id = '65'
AND g.is_delete =0
AND g.is_on_sale =1
GROUP BY g.goods_id
order by sell_num desc;