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);
- 插入數(shù)據(jù)
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');
- 題意----根據(jù)訂單商品表(order_goods)列出商品(goods)賣的數(shù)量
邏輯是----先合并,再根據(jù)合并后的表進行g(shù)roupby,進行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
- 根據(jù)訂單商品表(order_goods)列出商品賣的數(shù)量,且列出該類別
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;
- 根據(jù)訂單商品表(order_goods)、指定類別ID(cat_id =1),列出商品賣的數(shù)量,且列出該類別
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;