让PostgreSQL支持没有别名的子查询(Oracle兼容)

前端之家收集整理的这篇文章主要介绍了让PostgreSQL支持没有别名的子查询(Oracle兼容)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Postgresql里我们随便运行一个不带别名的子查询

  1. postgres=#select*from(select*frompg_class);
  2. ERROR:subqueryinFROMmusthaveanalias
  3. LINE1:select*from(select*frompg_class);
  4. ^
  5. HINT:Forexample,FROM(SELECT...)[AS]foo.
  6. postgres=#

而带子查询的是这样:

  1. postgres=#selectamnamefrom(select*frompg_am)asalimit3;
  2. amname
  3. --------
  4. btree
  5. hash
  6. gist
  7. (3rows)
  8.  
  9. postgres=#

Oracle下,有无别名均可:

  1. sql>select*from(select*fromtab);
  2.  
  3. TNAME TABTYPE CLUSTERID
  4. -----------------------------------------------
  5. COUNTRIES TABLE
  6. DEPARTMENTS TABLE
  7. EMPLOYEES TABLE
  8. EMP_DETAILS_VIEW VIEW
  9. JOBS TABLE
  10. JOB_HISTORY TABLE
  11. LOCATIONS TABLE
  12. REGIONS TABLE
  13.  
  14. 8rowsselected.
  15.  
  16. sql>

没什么大的影响,但如果遇到Oracle程序向PG迁移,改起来就有点罗嗦,这时候我们不妨让PG变化一下。

这个目标是非常明确,直接去源代码里边:grep -r "subquery in FROM must have an alias",发现它在src/backend/parser/gram.y

沿着代码往下看,可以看到子查询别名为空时报错,办法就很直截了当了,未指定别名时给他产生一个。

出错代码替换为:

  1. Alias*a=makeNode(Alias);
  2. a->aliasname="alias_xxxx";
  3. n->alias=a;

编译之后运行:

  1. template1=#selectamnamefrom(select*frompg_am)limit3;
  2. amname
  3. --------
  4. btree
  5. hash
  6. gist
  7. (3rows)
  8.  
  9. template1=#

小打小闹修改PG就是如此简单,当然这里还有更多工作要做,比如别名应该随机生成而不是像这样写死。

  1. template1=#selectamnamefrom(select*frompg_am),(select*frompg_database);
  2. ERROR:tablename"alias_xxxx"specifiedmorethanonce
  3. template1=#

这肯定不是我们想要的结果


作为一个演示的例子,到此已经足够。


欢迎订阅国际社区中文邮件列表

欢迎使用云栖问答知识库



神州飞象(北京)数据科技有限公司,专业Postgresql产品与服务提供商

猜你在找的Postgre SQL相关文章