PostgresQL选择值在数组中的行

7cjasjjr  于 2023-04-11  发布在  PostgreSQL
关注(0)|答案(1)|浏览(145)

我有这张table

CREATE TABLE "public"."test" (
    "id" integer NOT NULL,
    "game_ids" integer[],
    CONSTRAINT "test_pkey" PRIMARY KEY ("id")
);

INSERT INTO "test" ("id", "game_ids") VALUES
(1, '{5,6,7}'),
(2, '{5,12,18}'),
(3, '{12,13,18}'),
(4, '{14,22,23}');

我想查询,以便获得game_ids列包含值12的所有行。
比如SELECT * FROM test WHERE game_ids CONTAIN 12;
我听说过ANY@>运算符,但它们似乎不起作用。我在所有这些尝试中都得到语法错误:

SELECT * FROM test WHERE ANY game_ids = 12;  // Error in query: ERROR: syntax error at or near "ANY"

SELECT * FROM test WHERE game_ids @> [12]; // Error in query: ERROR: syntax error at or near "["

SELECT * FROM test WHERE game_ids @> 12; // Error in query: ERROR: operator does not exist: integer[] @> integer

SELECT * FROM test WHERE 12 = ANY game_ids; // Error in query: ERROR: syntax error at or near "game_ids"

SELECT * FROM test WHERE game_ids >@ [12]; // Error in query: ERROR: syntax error at or near "["

有人知道我哪里做错了吗

dgtucam1

dgtucam11#

ANY运算符需要括号:

SELECT * FROM test WHERE 12 = ANY( game_ids );

要为@>运算符构造数组,请使用

SELECT * FROM test WHERE game_ids @> ARRAY[12];
-- or
SELECT * FROM test WHERE game_ids @> '{12}';

相关问题