簡體   English   中英

postgresql中的concat列選擇

[英]Concat columns in postgresql select

我嘗試了一些變化,但是從我對文檔的閱讀中,這個模式應該可以正常工作'' || val1 || val1 '' || val1 || val1 '' || val1 || val1 ...但我的結果是一個空列......

thedb=# \d buildings_propertyvalue;
                              Table "public.buildings_propertyvalue"
  Column   |          Type          |                              Modifiers                               
-----------+------------------------+----------------------------------------------------------------------
 id        | integer                | not null default nextval('buildings_propertyvalue_id_seq'::regclass)
 prop_id   | integer                | not null
 place_id  | integer                | not null
 float_val | double precision       | 
 int_val   | integer                | 
 char_val  | character varying(255) | 
 text_val  | text                   | 

thedb=# select * from buildings_propertyvalue limit 10;
 id  | prop_id | place_id | float_val | int_val | char_val | text_val 
-----+---------+----------+-----------+---------+----------+----------
 798 |       3 |      170 |           |     831 |          | 
   2 |      46 |      180 |           |       0 |          | 
 733 |       2 |      180 |        40 |         |          | 
 737 |      10 |      180 |           |       0 |          | 
 740 |       5 |      345 |       100 |         |          | 
 742 |      10 |      345 |           |       0 |          | 
  11 |       2 |      170 |        50 |         |          | 
 744 |      11 |      345 |         0 |         |          | 
 746 |      14 |      345 |           |         | 52       | 
 749 |      46 |      348 |           |       0 |          | 
(10 rows)

thedb=# select prop_id, place_id, '' || float_val || int_val || char_val || text_val as val from buildings_propertyvalue limit 10;
 prop_id | place_id | val 
---------+----------+-----
       3 |      170 | 
      46 |      180 | 
       2 |      180 | 
      10 |      180 | 
       5 |      345 | 
      10 |      345 | 
       2 |      170 | 
      11 |      345 | 
      14 |      345 | 
      46 |      348 | 
(10 rows)

NULL與非空字符串連接會產生NULL

由於您的*_val列可以為空,因此可能正在發生的事情。

試試這個:

'' || COALESCE(float_val::TEXT, '') || COALESCE(int_val::TEXT, '') || COALESCE(char_val, '') || COALESCE(text_val, '')

或者,如果您最多只能有一個非空值,只需:

COALESCE(float_val::TEXT, int_val::TEXT, char_val, text_val, '')

請注意,在PostgreSQL ,與其他引擎不同, TEXTVARCHAR相比沒有任何缺點 分離TEXTVARCHAR數據毫無意義。

將NULL值連接到任何其他值會產生NULL。 看起來連接的某些列是可空的,因此您需要在它們周圍包裝COALESCE函數以在空字符串或其他占位符值為NULL時強制它們。

暫無
暫無

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

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