我正在使用一个现有的数据库,它有一个带有来自另一个表的ID的数组字段(Phones),我是这类功能的新手,我怎样才能获得记录到User-的所有Public_Phone记录>手机阵列?
用户表
+---------------------------------------+
|ID | User | Phones(int array) | Email|
+---------------------------------------+
| 1 | 11922 | {12,23,56} | none |
Public_Phone表
+-------------------------------------+
|ID | Location | Color | AR | Line_FK |
+-------------------------------------+
注意:数据库最近升级到9.4
提前谢谢。
计算@nullReference评论我正在尝试这个
SELECT *
FROM Public_Phone pp
WHERE pp.id IN (1,5)
这是工作
但是使用子查询查询用户[3]:
SELECT *
FROM Public_Phone pp
WHERE pp.id IN( SELECT Phones FROM User u WHERE u.id=3)
我得到了:
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
ERROR: operator does not exist: integer = integer[]
使用
SELECT *
FROM Public_Phone pp
WHERE pp.id = ANY( SELECT Phones FROM User u WHERE u.id=3)
是一样的
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
********** Error **********
ERROR: operator does not exist: integer = integer[]
答案 0 :(得分:1)
尝试以下查询:
SELECT *
FROM Public_Phone pp
JOIN User u ON pp.id = ANY(u.Phones)
WHERE u.id = 3
答案 1 :(得分:0)
无需昂贵的连接即可更有效地完成此操作。 您需要做的就是使用 UNNEST 将数组转换为行
SELECT *
FROM Public_Phone
WHERE id IN( SELECT UNNEST("Phones") FROM User WHERE id = 3 )
参考 https://lerner.co.il/2014/05/24/turning-postgresql-arrays-rows-unnest/