zoukankan      html  css  js  c++  java
  • postgresql----SELECT

    示例1.简单查询

    使用*查询表所有的字段,也可以指定字段名查询

    test=# select * from tbl_insert;
     a | b  
    ---+----
     3 | sd
     4 | ff
    (2 rows)
    
    test=# select a from tbl_insert;
     a 
    ---
     3
     4
    (2 rows)

    示例2.聚合函数

    聚合函数是使用多行数据,经过计算得到一个结果,如count,max,min,avg,sum等。聚合函数不能与具体字段出现在SELECT子句中,关系型数据库的表本就是每一列行数是相等的,聚合函数结果固定只有一行,而具体字段行数是不固定的。

    test=# select * from tbl_insert;
      a   | b  
    ------+----
        3 | sd
        4 | ff
     NULL | sd
    (3 rows)
    
    test=# select sum(a),count(*),count(a),count(1),avg(a),max(a),min(a) from tbl_insert;
     sum | count | count | count |        avg         | max | min 
    -----+-------+-------+-------+--------------------+-----+-----
       7 |     3 |     2 |     3 | 3.5000000000000000 |   4 |   3
    (1 row)

    从结果中看到sum(a)=7,count(*)=3,count(a)=2,count(1)=3,avg(a)=3.5,指定字段使用count(a)和avg(a)跳过a是NULL的行。

    示例4.WHERE条件查询

     WHERE后面可以跟多种逻辑判断,如某个字段>,>=,<,<=,=,!=,between A and B(即>=A and <=B),in,not in,exists,not exists,like,ilike等,逻辑与使用AND,逻辑或使用OR,不等于使用!=或<>,但是我经常记不住逻辑符的优先级,尤其是where条件比较复杂时脑袋就大了,所以我习惯在多个逻辑符使用小括号()。

    test=# create table tbl_insert(a int,b varchar(32));
    CREATE TABLE
    test=# insert into tbl_insert(a,b) values (1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e');
    --查询a等于1的行 test=# select * from tbl_insert where a = 1; a | b ---+--- 1 | a (1 row) --查询a不等于2的行 test=# select * from tbl_insert where a != 2; a | b ---+--- 1 | a 3 | c 4 | d 5 | e (4 rows) test=# select * from tbl_insert where a <> 2; a | b ---+--- 1 | a 3 | c 4 | d 5 | e (4 rows) --查询a大于等于3的行 test=# select * from tbl_insert where a >= 3; a | b ---+--- 3 | c 4 | d 5 | e (3 rows) --查询a大于等于1且小于等于3的行 test=# select * from tbl_insert where a >= 1 and a <= 3; a | b ---+--- 1 | a 2 | b 3 | c (3 rows) test=# select * from tbl_insert where a between 1 and 3; a | b ---+--- 1 | a 2 | b 3 | c (3 rows) --查询a大于3且b是'd'或'e'的行 test=# select * from tbl_insert where a > 3 and (b='d' or b = 'e'); a | b ---+--- 4 | d 5 | e (2 rows) test=# select * from tbl_insert where a > 3 and b in ('d','e'); a | b ---+--- 4 | d 5 | e (2 rows) --查询a大于3或b是'd'或b是'e'的行 test=# select * from tbl_insert where a > 3 or (b='d' or b = 'e'); a | b ---+--- 4 | d 5 | e (2 rows) test=# select * from tbl_insert where a > 3 or b in('d','e'); a | b ---+--- 4 | d 5 | e (2 rows)

    不建议使用如下方式查询,当表中数据量较大,or条件中数量太多,会有明显的性能影响。

    b='d' or b = 'e' or b = or b = or b = ...

    建议使用in解决此问题,即

    b in ('d','e',...)

  • 相关阅读:
    CentOS7中Tomcat的安装和配置
    CentOS7中JDK的安装和配置
    Linux基本指令
    MySQL数据库索引:索引介绍和使用原则
    MongoDB基础篇2:数据库/用户/数据集合的增删改
    MongoDB基础篇1:安装和服务配置
    JSTL fn:replace()函数替换 换行符
    LeetCode440. 字典序的第K小数字
    kubeadm搭建kubernetes-1.13.2集群
    kubernetes(k8s)kubectl使用详解
  • 原文地址:https://www.cnblogs.com/alianbog/p/5615163.html
Copyright © 2011-2022 走看看