2013-07-15 126 views
4

產品名稱包含由空格分隔的單詞。 第一個字是品牌規模第二等如何從Postgres中的字符串中提取特定單詞

如何提取字符串的那些話,情商如何實現像查詢:

select 
    id,  
    getwordnum(prodname,1) as size, 
    getwordnum(prodname,2) as brand 
    from products 
where ({0} is null or getwordnum(prodname,1)={0}) and 
    ({1} is null or getwordnum(prodname,2)={1}) 


create table product (id char(20) primary key, prodname char(100)); 

如何Postgres的創建getwordnum()函數或應該有的子( )或其他函數直接在這個查詢中使用以提高速度?

+0

什麼?「剛剛有人」是想說:你的數據庫模型是錯誤的。閱讀正常化 –

回答

5

你可以嘗試使用功能split_part

select 
    id,  
    split_part(prodname, ' ' , 1) as size, 
    split_part(prodname, ' ', 2) as brand 
    from products 
where ({0} is null or split_part(prodname, ' ' , 1)= {0}) and 
    ({1} is null or split_part(prodname, ' ', 2)= {1}) 
0
select 
    id,  
    prodname[1] as size, 
    prodname[2] as brand 
from (
    select 
     id, 
     regexp_split_to_array(prodname, ' ') as prodname 
    from products 
) s 
where 
    ({0} is null or prodname[1] = {0}) 
    and 
    ({1} is null or prodname[2] = {1}) 
相關問題