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',...)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM