【问题标题】:PostgreSQL compare with substring doesn't workPostgreSQL 与子字符串比较不起作用
【发布时间】:2012-07-25 10:33:41
【问题描述】:

我想从 2 个表中选择,其中第二个 id 与第一个 id 的前 4 个字符相等

SELECT a.*, b.*, substring(a.my_id from 1 for 4)::integer as number
   FROM table1 as a
INNER Join table2 as b ON(b.id_2=number) where my_id = 101
                                 ^
It produces an error here        | 

错误:“数字”列不存在

SQL 状态:42703

字符:189

【问题讨论】:

  • SELECT 列表中的别名在 FROM 列表中不起作用。将 substring(a.my_id from 1 for 4)::integer 移动到您的 ON 条件。

标签: postgresql select substring inner-join


【解决方案1】:

你不能使用这样的别名,你需要一个派生表:

select *
from (
   SELECT t1.*, 
          substring(t1.my_id::text from 1 for 4)::integer as number
   FROM table1 t1
) as a 
inner join table2 as b ON (b.id_2 = a.number) 
where my_id = 101

将用作外键的数字作为 varchar 列的一部分存储是一个非常非常丑陋的设计。该数字应该是 table1 中自己的一列。

【讨论】:

  • 在这种情况下,它给了我错误:在第二个选择中的表“a”的子查询中缺少 FROM 子句条目
  • @Alex: 抱歉复制和粘贴太多(但有一点想法你可以自己修复)
  • 但是它并没有解决我的问题(函数 pg_catalog.substring (integer, integer, integer) 不存在
  • @Alex:my_id 是什么数据类型?
  • @Alex:你不喜欢阅读手册,是吗?子字符串是一个适用于字符串而不是数字的函数。请参阅我的编辑。重新考虑你的设计。仅使用数字的一部分作为对另一个表的引用绝对是疯狂的。
猜你喜欢
  • 2011-09-20
  • 2014-04-03
  • 2012-01-22
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多