当前位置 博文首页 > 用心编码:mysql数据库基础(二)

    用心编码:mysql数据库基础(二)

    作者:[db:作者] 时间:2021-09-07 13:25

    一、条件过滤

    • not 条件和() 条件
    1.() 的用法
    2.not 的用法
    where end is null and not (title = 'hello');
    • 子查询作为临时表
    dept_id = (select dept_id from department where name = 'loans')
    • 不相等条件 <> / !=
    • 范围条件 between
    where date between '2005-01-01' and '2005-12-31';
    1.between 条件包含前后值,例如上面包含2005-01-01 当天和2005-12-31 当天。
    2.如果between 前面的值比后面的值大,查询时不会报错而是返回空集。
    3.字符串也可以当作范围来使用。
    • 成员条件(类似于枚举): in
    比如:select * from account where product_cd = 'A' or product_cd = 'B' or product_cd = 'D';
    可以采用:
    where product_cd in ('A','B','C'); 
    • 匹配条件 left() / right();
    处理部分字符串匹配问题:比如可以找到以T开头的字符串或者以B结尾的字符串
    ... where left(lname,1) = 'T' or right(lname,1) = 'B';
    • 通配符的使用
    _ : 一个字符
    % : 任意数目的字符(包含0个字符)
    • 正则表达式匹配 regexp
    where lname regexp '^[FG]';以字符F或者G开头。
    • null
    1.null 表示值的缺失
    没有合适的值、值为确定、值为定义。
    2.表达式的值可以为null,但是不能等于null。一般采用 is null/ is not null;
    3.两个null值不能彼此判断为相等。

    二、多表查询

    • 内查询 inner join … on …
    1.select e.lname,d.name  from  employee e join department d;
    多表连接如果没有明确指出如何连接,默认采用内链接。
    没有明确指出连接条件,结果返回笛卡尔积。也就是说两张表所有置换,若employee 有5条信息,department 表有3条信息,那么结果会返回 5 * 3 = 15 条结果。
    • inner join 连接失败
    select e.fname,e.lname,d.name from employee e inner join department d on e.dept_id = d.dept_id;
    如果一个表中的dept_id 列中存在某个值,但是该值在另一个表中的dept_id中不存在,那么相关行就会连接失败。在结果集中值存在两表相互存在的行数据。
    
    内链接是查询交叉部分的数据,假如连接条件为a.bid = b.id 那么结果中只会出现,a.bid 的值既存在a表中也存在b表中的数据。
    
    如果想要显示在a.bid 存在于a表中的值,但是不存在b表中的值的行,可以采用外连接 outer join ... on...
    • 连接条件和过滤条件
    1.连接条件 on 后面的条件
    
    2.过滤条件 where 后面的条件
    
    select a.account_id,a.cust_id,a.open_date,a.product_cd from account a inner join employee e on a.open_emp_id = e.emp_id inner join branch b on e.assigned_branch_id = b.branch_id where e.start_date < '2007-01-01' and (e.title = 'Taller' or e.title = 'Head Teller') and b.name = 'Woburn Branch';
    • 连接顺序
    SQL 是一种非过程化的语言,也就是说只需要描述要获取的数据对象,而如何以最好的方式执行查询则由数据库服务器负责,服务器根据所收集的数据库对象信息,在多表中选择一个作为开始点(驱动表),然后确定连接其它表的顺序。、
    from字句各表出现的顺序不重要。
    • 自连接 同一张表相互连接
    select e.fname,e.lname,e_mgr.fname,e_mgr.lname from employee e inner join employee e_mgr on e.superior_emp_id = e_mgr.emp_id;
    cs
    下一篇:没有了