• mysql学习之基础篇04


    五种基本子句查询

    查询是mysql中最重要的一环,我们今天就来说一下select的五种子句中的where条件查询:

     首先我们先建立一张商品表:goods

    由于商品数目太多,我就不一一列举了。

    在这里我说一下这些列名都是什么意思:

    goods_id 主键;goods_name 商品名称;cat_id 商品所属栏目;goods_nummber 商品库存;shop_price 本店价格;market_pprice 市场价格;click_count 点击量。

    我们取出主键为32的商品:

    select * from goods where goods_id=32;select * from goods where goods_id=32;

    我们注意,一定要把where表达式理解清楚,只要where后面的条件为真,那么语句就执行

    我们看到主键为32的商品本店价格为3010,市场价格为3612,

     那么我们也可以用

    select * from goods where shop_price=3010 and market_price=3612;

    来取出它

    我们来取出商品栏目不等于3的商品:

    select * from goods where cat_id !=3;

    取出本店价格小于3000的商品:

    select * from goods where shop_price<3000;

     

    取出商品栏目是4和11的商品:

    select * from goods where cat_id in (4,11);

     

    取出商品本店价格在100500之间的商品(含边界):

    select * from goods where shop_price between 100 and 500;

     

    取出商品栏目不在311的商品(andnot in分别实现)

    select * from goods where cat_id !=3 and cat_id !=11;

     

    select * from goods where cat_id not in (3,11);

     

     取出第三个栏目下面本店价格<1000>3000,并且点击量>5的商品:

    在这里我们使用括号来控制优先级:

    select * from goods where cat_id=3 and (shop_price<1000 or shop_price>3000) and click_count>5;

     

    模糊查询:like

    %通配任意字符

    _匹配单一字符

    我们想查出名称以诺基亚为开头的商品:

    select * from goods where goods_name like '诺基亚%';

     

    我们想查出名称以诺基亚为开头,并且后面只有三个字符的商品:

    select * from goods where goods_name like '诺基亚___';

     

    把列当成变量,既然是变量,那就可以进行运算,比较

    取出商品id,商品名,本店价格比市场价格省的钱:

    select goods_id,goods_name,market_price - shop_price from goods ;

     

    这种结果叫做广义投影。

    我们还可以给列差价起个名字叫做discount但是这个列并不在原表中存在,只存在于结果中:

    select goods_id,goods_name,market_price-shop_price as discount from goods;

    如果要对结果继续进行查询,需要用having:

    比如我们想从上面的结果中取出差价大于200的商品:

    select goods_id,goods_name,market_price-shop_price as discount from goods having discount>200;

    一定注意这里的having不能换成where,否则会报错,因为我们是对结果进行再次查询,而不是从原来的表里面直接查询,因为原来的表里面没有discount这一列。

    接下来我们用一道面试题来练习:

    把下面表中[20,29]的值改为20[30,39]的值改为30

    这道题的核心在于我们要能想到把列当成一个变量来进行运算,对其除以10取模再乘10。

    update mian set num=floor(num/10)*10 where num between 20 and 39;

     

    再来做道练习题:goods表中商品名为‘诺基亚xxxx’的商品名称显示为‘HTCxxxx’。

    提示:用到两个函数,一个是截取字符串函数substring(),一个是连接字符串函数concat()。

    select goods_name,concat('HTC',substring(goods_name,4)) from goods where goods_name like '诺基亚%' ;

  • 相关阅读:
    HDU 1086 You can Solve a Geometry Problem too(水题,判断线段相交)
    2011ACM福州网络赛第一题 A Card Game(水题)
    Lottery hdu1099
    卡特兰数 ACM 数论
    (转)CXF的Exception问题
    简单PS合成图像(抹去某个人等)
    摄影技巧
    PS中文字变形
    螺旋阵(递归和非递归)
    路径与滤镜和自定义工具
  • 原文地址:https://www.cnblogs.com/wanghaoyu666/p/11268485.html
Copyright © 2020-2023  润新知