MySQL燕十八老师课程笔记:第六课:商品表的各种按条件查询

老师下了ecshop,我看有弹幕同学说:“可以下,但没必要”,我就没下。

查询:

#先模拟ecshop建一个小型的商品表
create table goods(
goods_id mediumint(8) unsigned not null auto_increment,
cat_id smallint(5) unsigned not null default '0',
goods_sn varchar(60) not null default '',
goods_name varchar(120) not null default '',
click_count int(10) unsigned not null default '0',
goods_number smallint(5) unsigned not null default '0',
market_price decimal(10,2) unsigned not null default '0.00',
shop_price decimal(10,2) unsigned not null default '0.00',
add_time int(10) unsigned not null default '0',
is_best tinyint(1) unsigned not null default '0',
is_new tinyint(1) unsigned not null default '0',
is_hot tinyint(1) unsigned not null default '0',
primary key(goods_id)
)engine myisam charset utf8;

查询商品主键是32 的商品:

select goods_id,goods_name,shop_price from goods where goods_id = 32;

查出不属于第三个栏目的所有商品:

#即商品栏目cat_id不等于3
select goods_id,cat_id,goods_name from goods where cat_id != 3;


# !=还有另一个写法:<>   这两句语句等价。
select goods_id,cat_id,goods_name from goods where cat_id <> 3;

查出本店价格高于3000元的商品:

select goods_id,goods_name,shop_price from goods where shop_price>3000;

查出本店价格小于或等于100元的商品:

select goods_id, goods_name,shop_price from goods where shop_price<=100;

取出第4个栏目和第11个栏目的商品,且不能用or:

select goods_id,cat_id,goods_name from goods 
where cat_id in (4,11);
#表示cat_id在(411)这个集合里都满足。

取出商品价格在100和500之间的商品,且不能用and:

select goods_id, goods_name,shop_price from goods where shop_price
between 100 and 500;  #between and 包括边界值(前后边界都包含)!

观察上述两例:

  1. name in (a,d,c,f) 是指 name 值只要在(a,d,c,f)这个集合中,就满足条件。
  2. between and 是一个范围,in 是一个散点集合。

取出不属于第3个栏目,也不属于第11个栏目的商品,用not in 和 and 分别实现:

select goods_id, cat_id,goods_name from goods
where cat_id not in(3,11);
#用and 来写:
select goods_id,cat_id,goods_name from goods
where cat_id != 3 and cat_id !=11;

取出价格大于100且小于300,或者大于4000且小于5000的商品:

select goods_id,cat_id,goods_name,shop_price from goods
where shop_price>100 and shop_price < 300 
or shop_price >4000 and shop_price < 5000;
#由此可知,and 的优先级比 or 的优先级要高!

取出第3个栏目下,价格小于1000或者大于3000,同时点击量大于等于5的商品:

select goods_id,goods_name,shop_price,cat_id,click_count from goods 
where cat_id = 3 
and (shop_price <1000 or shop_price >3000) and click_count >=5;
#重点:由于优先级的问题,在中间价格的判断中要多加一个括号,保证逻辑语言的准确性。

查出名称以 诺基亚 开头的商品:

#模糊查询!
select goods_id,goods_name from goods
where goods_name like '诺基亚%'; 
# 若逛商场时,看了一款手机,诺基亚Nxx系列,具体型号记不清了,请查出:
select goods_id,goods_name from goods
where goods_name like '诺基亚__'; 
#此时把 % 换成两个_(下划线)即可。

注意上面是两个下划线!!!

like 模糊查询:
% 通配任意字符 _ 通配单一字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值