2011-11-17 52 views
0
在加入操作期間由另一個值替換NULL

當運行使用HSQLDB 2.2.5,的results.csv內容下面的腳本(q.sql)成爲以下:在HSQLDB

results.csv

C1,C2 
[null],e 
a,b 

q.sql:

DROP TABLE "PUBLIC"."TABLE1" IF EXISTS; 

CREATE TABLE "PUBLIC"."TABLE1" (
    "C1" VARCHAR(10), 
    "C2" VARCHAR(10), 
    "C3" VARCHAR(10) 
); 

INSERT INTO "PUBLIC"."TABLE1" ("C1", "C2", "C3") VALUES ('a', 'b', 'c'); 
INSERT INTO "PUBLIC"."TABLE1" ("C1", "C2", "C3") VALUES ('d', 'e', 'f'); 

DROP TABLE "PUBLIC"."TABLE2" IF EXISTS; 

CREATE TABLE "PUBLIC"."TABLE2" (
    "C1" VARCHAR(10), 
    "C2" VARCHAR(10), 
); 

INSERT INTO "PUBLIC"."TABLE2" ("C1", "C2") VALUES ('a', 'b'); 
INSERT INTO "PUBLIC"."TABLE2" ("C1", "C2") VALUES ('u', 'v'); 

DROP TABLE "PUBLIC"."TABLE3" IF EXISTS; 

CREATE TABLE "PUBLIC"."TABLE3" (
    "C1" VARCHAR(10), 
    "C2" VARCHAR(10) 
); 

INSERT INTO "PUBLIC"."TABLE3" (
    "C1", 
    "C2" 
) 
SELECT 
(SELECT 
"T2"."C1" AS "T2C1" 
FROM "PUBLIC"."TABLE2" "T2" 
WHERE "T2"."C1" = "T1"."C1") AS "T2C1", 
"T1"."C2" AS "T1C2" 
FROM "PUBLIC"."TABLE1" "T1" 
ORDER BY "T2C1", "T1C2"; 

* *DSV_COL_DELIM=, 
* *DSV_ROW_DELIM=\n 
* *DSV_TARGET_FILE=results.csv 

\x "PUBLIC"."TABLE3" 

哪有我改變我的腳本,使得「[null]」被替換爲「?」在生成的CSV文件中?

+0

所以沒有建議的解決方案滿足您的需求?因爲鏈接直接來自hSQLDB文檔,所以我有些驚訝。它的實現當然不是函數本身。 – xQbert

回答

0

不是插入表中的值,而是使用case語法插入來檢查值是否爲空。

事情是這樣的:

case when value = [null] then ? else variable end 
+0

案例陳述將等同於'COALESCE'和'COALESCE'不起作用。所以,如果您嘗試使用case語句,您會發現它也不起作用。 – reprogrammer

+0

當然,你的意思是說'CASE當值爲NULL時'?' ELSE值END'。 (「= NULL」總是假,裸體?是參數標記,「[null]」是輸出顯示不是輸入語法的工件,「值」和「變量」表示不同的列,這不是OP想要的) – pilcrow

1

取決於用到dbengine:

爲HSQL ...任何3個工作的依據:hSQLDB.org

COALESCE(MOST)

NVL (oracle)

ifNull(mysql) 編輯添加(...(哎呀,我忘了!)

SELECT 
coalesce((SELECT 
"T2"."C1" AS "T2C1" 
FROM "PUBLIC"."TABLE2" "T2" 
WHERE "T2"."C1" = "T1"."C1"),'?') AS "T2C1", 
"T1"."C2" AS "T1C2" 
FROM "PUBLIC"."TABLE1" "T1" 
ORDER BY "T2C1", "T1C2"; 
+0

我試過'COALESCE'和'IFNULL',但是他們沒有工作。 HSQLDB抱怨說SELECT是一個未知對象。 – reprogrammer

+0

這幾乎是正確的,但需要一個額外的開放parens合併後'SELECT COALESCE((SELECT# – fredt

+0

thx爲該fredt糾正。 – xQbert