PostgreSQL OR IN ANY

前端之家收集整理的这篇文章主要介绍了PostgreSQL OR IN ANY前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. create table@H_502_3@

  1. postgres=# create table tb5 (id integer,age integer);
  2. CREATE TABLE
  1. postgres=# \d tb5
  2. Table "public.tb5"
  3. Column | Type | Modifiers
  4. --------+---------+-----------
  5. id | integer |
  6. age | integer |
2. insert example data
  1. postgres=# insert into tb5 select generate_series(1,10),random()*10::integer;
  2. INSERT 0 10
  1. postgres=# select * from tb5;
  2. id | age
  3. ----+-----
  4. 1 | 6
  5. 2 | 2
  6. 3 | 1
  7. 4 | 7
  8. 5 | 8
  9. 6 | 9
  10. 7 | 0
  11. 8 | 6
  12. 9 | 10
  13. 10 | 0
  14. (10 rows)
3. test 'OR'
  1. postgres=# select * from tb5 where age=1 or age=2 or age=7;
  2. id | age
  3. ----+-----
  4. 2 | 2
  5. 3 | 1
  6. 4 | 7
  7. (3 rows)
  1. postgres=# explain analyze select * from tb5 where age=1 or age=2 or age=7;
  2. QUERY PLAN
  3. -----------------------------------------------------------------------------------------------
  4. Seq Scan on tb5 (cost=0.00..85.25 rows=64 width=8) (actual time=0.008..0.010 rows=3 loops=1)
  5. Filter: ((age = 1) OR (age = 2) OR (age = 7))
  6. Rows Removed by Filter: 7
  7. Total runtime: 0.024 ms
  8. (4 rows)
4. test 'IN'
  1. postgres=# select * from tb5 where age in(1,2,7);
  2. id | age
  3. ----+-----
  4. 2 | 2
  5. 3 | 1
  6. 4 | 7
  7. (3 rows)
  1. postgres=# explain analyze select * from tb5 where age in(1,7);
  2. QUERY PLAN
  3. -----------------------------------------------------------------------------------------------
  4. Seq Scan on tb5 (cost=0.00..69.12 rows=64 width=8) (actual time=0.007..0.008 rows=3 loops=1)
  5. Filter: (age = ANY ('{1,7}'::integer[]))
  6. Rows Removed by Filter: 7
  7. Total runtime: 0.020 ms
  8. (4 rows)

note: the 'OR' operation in explain be changed the 'ANY' operation,It can be seen that postgresql handle the 'OR' operation by 'ANY' operation。@H_502_3@ 5. test 'ANY'

  1. postgres=# select * from tb5 where age=ANY('{1,7}');
  2. id | age
  3. ----+-----
  4. 2 | 2
  5. 3 | 1
  6. 4 | 7
  7. (3 rows)
  1. postgres=# explain analyze select * from tb5 where age=ANY('{1,7}');
  2. QUERY PLAN
  3. -----------------------------------------------------------------------------------------------
  4. Seq Scan on tb5 (cost=0.00..69.12 rows=64 width=8) (actual time=0.008..0.009 rows=3 loops=1)
  5. Filter: (age = ANY ('{1,7}'::integer[]))
  6. Rows Removed by Filter: 7
  7. Total runtime: 0.020 ms
  8. (4 rows)


@H_502_3@

ConClusion: The IN operation can be change the OR operation,and the OR operation can be changed the ANY operation. So,when we use the IN or OR operaion,@H_502_3@

we can use ANY instead of them.@H_502_3@

猜你在找的Postgre SQL相关文章