where条件使用

最近更新时间: 2025-02-18 16:02:00

  • 单条件查询。
  • 复制
    复制成功
postgres=# select * from tbase where id=1;
 id |          nickname           
----+-----------------------------
  1 | hello TDSQL PG
  1 | TDSQL PG分布式数据库的时代来了
  • 多条件and。
  • 复制
    复制成功
postgres=# select * from tbase where id=1 and nickname like '%h%';
 id |  nickname   
----+-------------
  1 | hello TDSQL PG
(1 row)
  • 多条件or。
  • 复制
    复制成功
postgres=# select * from tbase where id=2 or nickname like '%h%';    
 id |  nickname   
----+-------------
  1 | hello TDSQL PG
  2 | TDSQL PG好
(2 rows)
  • ilike不区分大小写匹配。
  • 复制
    复制成功
postgres=# create table t_ilike(id int,mc text);
CREATE TABLE
postgres=# insert into t_ilike values(1,'TDSQL PG'),(2,'TDSQL PG');
INSERT 0 2
postgres=# select * from t_ilike where mc ilike '%tb%';
 id |  mc   
----+-------
  1 | TDSQL PG
  2 | TDSQL PG
(2 rows)
  • where条件也能支持子查询。
  • 复制
    复制成功
postgres=# select * from tbase where id=(select (random()*2)::integer from tbase order by random() limit 1);      
 id | nickname 
----+----------
(0 rows)

postgres=# select * from tbase where id=(select (random()*2)::integer from tbase order by random() limit 1);      
 id |          nickname           
----+-----------------------------
  1 | hello TDSQL PG
  1 | TDSQL PG分布式数据库的时代来了
(2 rows)
  • null值查询方法。
  • 复制
    复制成功
postgres=# select * from tbase where nickname is null;
 id | nickname 
----+----------
  4 | 
(1 row)

postgres=# select * from tbase where nickname is not null;
 id |          nickname           
----+-----------------------------
  1 | hello TDSQL PG
  2 | TDSQL PG好
  1 | TDSQL PG分布式数据库的时代来了
(3 rows)
  • exists,只要有记录返回就为真。
  • 复制
    复制成功
postgres=#  create table t_exists1(id int,mc text);
CREATE TABLE

postgres=# insert into t_exists1 values(1,'TDSQL PG'),(2,'TDSQL PG');  
INSERT 0 2

postgres=# create table t_exists2(id int,mc text); 
CREATE TABLE

postgres=# insert into t_exists2 values(1,'TDSQL PG'),(1,'TDSQL PG');
INSERT 0 2

postgres=# select * from  t_exists1 where  exists(select 1 from t_exists2 where t_exists1.id=t_exists2.id) ;
 id |  mc   
----+-------
  1 | TDSQL PG
(1 row)
  • exists等价写法。
  • 复制
    复制成功
postgres=# select t_exists1.* from t_exists1,(select distinct id from t_exists2) as t where t_exists1.id=t.id;;
 id |  mc   
----+-------
  1 | TDSQL PG
(1 row)