2012-07-25 79 views
0

我想從2表,其中第二個ID是從第一ID前4個字符等於選擇的PostgreSQL與子比較不起作用

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

+0

SELECT'列表中的別名在'FROM'列表中不起作用。將'子字符串(a.my_id從1開始4):: integer'移動到'ON'狀態。 – LisMorski 2012-07-25 10:37:41

回答

3

不能使用這樣的,你需要一個派生表的別名:

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中它自己的一列。

+0

在這種情況下,它給了我錯誤:在第二個選擇內的表「a」的子查詢中缺少FROM子句條目 – Alex 2012-07-25 10:57:05

+0

@Alex:抱歉太多複製和粘貼(但有一點思考你可以自己修復) – 2012-07-25 11:08:23

+0

但它並沒有解決我的問題(函數pg_catalog.substring(整數,整數,整數)不存在 – Alex 2012-07-25 11:30:21