sql优化-错误强制类型转换导致索引失效

打印 上一主题 下一主题

主题 523|帖子 523|积分 1573

使用GaussDB数据库举行测试
创建下面表,仅有一个字段a为integer类型。声明其为主键,数据库会默以为其创建索引。
  1. create table t1(
  2.     a int PRIMARY KEY
  3. );
复制代码
使用\d+检察表结构:
  1. gaussdb=# \d+ t1
  2.                           Table "public.t1"
  3. Column |  Type   | Modifiers | Storage | Stats target | Description
  4. --------+---------+-----------+---------+--------------+-------------
  5. a      | integer | not null  | plain   |              |
  6. Indexes:
  7.     "t1_pkey" PRIMARY KEY, btree (a) TABLESPACE pg_default
  8. Has OIDs: no
  9. Options: orientation=row, compression=no
复制代码
检察select * from t1 where a = 1;实行筹划:
  1. gaussdb=# explain select * from t1 where a = 1;
  2.                               QUERY PLAN
  3. -----------------------------------------------------------------------
  4. [Bypass]
  5. Index Only Scan using t1_pkey on t1  (cost=0.00..8.27 rows=1 width=4)
  6.    Index Cond: (a = 1)
  7. (3 rows)
复制代码
可以看到该语句顺利使用B树索引:Index Only Scan
检察select * from t1 where a::text = 1;实行筹划:
  1. gaussdb=# explain select * from t1 where a::text = 1;
  2.                      QUERY PLAN
  3. ----------------------------------------------------
  4. Seq Scan on t1  (cost=0.00..52.04 rows=12 width=4)
  5.    Filter: (((a)::text)::bigint = 1)
  6. (2 rows)
复制代码
可以看到该语句从使用B树索引,改为顺序扫描:Seq Scan。因为::text将a类型强转为text类型,也就无法使用索引。
::是类型转换操纵符,用于将一个表达式的值转换为另一种数据类型。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

篮之新喜

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表