簡體   English   中英

檢查PostgreSQL中逗號分隔列中的逗號分隔字符串

[英]Check comma separated string in comma separated column in postgresql

我有一個字符串searchval = "php,java,html"

我想檢查下表中column關鍵字中是否存在字符串中任何逗號分隔的值。

我的桌子

id     keyword
-----------------------------
1      java,php
2      jquery, javascript
3      java
4      php,jquery

與關鍵字(逗號分隔)匹配的任何searchval(逗號分隔)值都應返回ID。

因此結果應為:

1 (java,php is there),
3 (java is there),
4 (php is there)

我怎樣才能做到這一點?

首先,一個重要的建議: 不要將逗號分隔的字符串存儲在數據庫的列中。 這使處理變得不必要地困難。 您應該考慮創建一個單獨的關鍵字表,並在id列的表上有一個外鍵。

您可以將字符串轉換為ARRAY並進行重疊操作。但是,要逐個檢查值,則需要UNNEST進行比較。

SQL小提琴

PostgreSQL 9.6模式設置

CREATE TABLE t
    (id int, keyword varchar(18))
;

INSERT INTO t
    (id, keyword)
VALUES
    (1, 'java,php'),
    (2, 'jquery, javascript'),
    (3, 'java'),
    (4, 'php,jquery')
;

查詢1

SELECT id, 
       string_agg(lang, ',') AS keyword 
FROM   t, 
       unnest(string_to_array(keyword, ',')) AS k(lang) 
WHERE  lang = ANY ( string_to_array('php,java,html', ',') ) 
GROUP  BY id 
ORDER  BY id

結果

| id |  keyword |
|----|----------|
|  1 | java,php |
|  3 |     java |
|  4 |      php |

您可以輕松地將逗號分隔的列表轉換為數組,然后使用Postgres的數組函數測試是否包含:

select id
from the_table
where string_to_array(keyword,',') && array['php','java','html'];

重疊運算符&&檢查從關鍵字列表創建的數組是否包含右側數組中的元素。

在線示例: http : //rextester.com/VNWP17762

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM