• mysql---where子查询、form子查询、exists子查询


    1.什么是子查询?

    当一个查询是另一个查询的条件时,称之为子查询。

    2.子查询有什么好处?

    子查询可以使用几个简单命令构造功能强大的复合命令。

    那么,现在让我们一起来学习子查询。

    3.where型的子查询

    给它个定义吧:where型的子查询就是把内层查询的结果当作外层查询的条件。

    现在,我们来查询文章表里每组主题分类下评论最多的文章。

    给定表如下:

    create table article(
    article_id int(3),
    article_title varchar(50),
    article_content text,
    article_comments int(3),
    articlecategory_id int(3)
    );
    insert into article values(1,"fff1","contteee",55,1);
    insert into article values(2,"fff2","conttffffffeee",15,2);
    insert into article values(3,"fff3","conttdgfdfdsfeee",515,1);
    insert into article values(4,"fff4","conttesdfsdfsee",505,1);
    insert into article values(5,"fff5","conttesdfsdfee",545,2);
    insert into article values(6,"fff6","conttesdfsee",575,2);
    insert into article values(7,"fff7","conttesdfsdee",5,1);
    insert into article values(8,"fff8","conttesdfsdfee",77,1);

    如:select article_id,article_title,article_content from article where article_comments in (select max(article_comments) from article group by articlecategory_id);

    4.from子查询

    定义:from子查询就是把子查询的结果(内存里的一张表)当作一张临时表,然后再对它进行处理。

    from子查询解决上面问题

    如:select tmp.article_id,tmp.article_content,article_comments from ( select * from article order by articlecategory_id,article_comments desc ) as tmp group by tmp.articlecategory_id;

    5.exists子查询

    定义:exists子查询就是对外层表进行循环,再对内表进行内层查询。和in ()差不多,但是它们还是有区别的。主要是看两个张表大小差的程度。

    若子查询表大则用exists(内层索引),子查询表小则用in(外层索引);

    效率的区别就在于使用的索引(where后面的变量就是我们使用的索引)不同摆了,我们可以对大表使用索引提高搜索速度。

  • 相关阅读:
    Postgres的TOAST技术
    Postgresql 分区表 一
    Postgresql 用户管理
    Linux FIO
    haproxy
    RHEL7/CentOS7 Network Service开机无法启动的解决方法
    Cockroachdb 四、用户管理及授权
    Cockroachdb 三、副本设置
    Cockroachdb 二、手动部署
    Cockroachdb 一、系统环境
  • 原文地址:https://www.cnblogs.com/a757956132/p/4311915.html
Copyright © 2020-2023  润新知