這是我的表:是否存在條款
ID COUNTRY_CODE_3D COUNTRY_CODE_2D TYPE_ID
1 "IND" "IN" 11
2 "CAN" "CA" 13
3 null null 17
我想選擇查詢將返回單行 如果COUNTRY_CODE_2D = 'CA'
(有效數據)返回第2行,否則返回第3行,其中COUNTRY_CODE_2D =null and TYPE_ID=17
這是我的表:是否存在條款
ID COUNTRY_CODE_3D COUNTRY_CODE_2D TYPE_ID
1 "IND" "IN" 11
2 "CAN" "CA" 13
3 null null 17
我想選擇查詢將返回單行 如果COUNTRY_CODE_2D = 'CA'
(有效數據)返回第2行,否則返回第3行,其中COUNTRY_CODE_2D =null and TYPE_ID=17
如果你可以把country_code_2d功能指數(NVL(country_code_2d,'EMPTY')
)
CREATE INDEX fidx_empty_null ON country_cnfg_tbl (NVL(country_code_2d,'EMPTY'));
,然後你可以
SELECT * FROM country_cnfg_tbl a
WHERE NVL(a.country_code_2d,'EMPTY') IN
(
SELECT NVL(b.country_code_2d,'EMPTY') FROM dual d
LEFT JOIN country_cnfg_tbl b on b.country_code_2d = 'CA'
)
或無連接(更便攜,因爲它不使用Oracle表DUAL
)
SELECT * FROM country_cnfg_tbl a WHERE NVL(a.country_code_2d,'EMPTY') IN
(
SELECT CASE WHEN count(*) = 0 THEN
'EMPTY'
ELSE
b.country_code_2d
END as country_code_2d
FROM country_cnfg_tbl b
WHERE b.country_code_2d = 'CA'
GROUP BY b.country_code_2d
)
感謝您的快速答覆。但如果'CAA'不存在,它會返回一個包含所有空值的行,我想要一行應該從這個country_cnfg_tbl表中返回一行,該表有b.country_code_2d = null –
好吧,列(已經更新了我的答案) –
如果b.country_code_2d ='CAA'不存在,它應該返回同一個表中的b.country_code_2d = null的行,如果可能的話,你可以給一個沒有任何連接的查詢,謝謝.. –
例無明確連接:
SELECT
*
FROM
country_cnfg_tbl
WHERE
nvl(country_code_2d,'xxx')
=
(select nvl(country_code_2d,'xxx')
from country_cnfg_tbl
where country_code_2d='CA')
但我向你保證,凱文·伯頓的答案是更好的:)我投它:))
謝謝凱文弗羅林你的幫助。
凱文,你給我的第二個查詢有1個錯誤。但我改變了一些東西,現在它的做工精細,凱文感謝您寶貴的投入,保持良好的工作:)
這是最終的查詢:
SELECT * FROM country_cnfg_tbl a WHERE NVL(a.country_code_2d,'EMPTY') IN
(SELECT
CASE
WHEN (select count(*) FROM country_cnfg_tbl WHERE country_code_2d IN ('CA') OR country_code_2d IS NULL) = 1 THEN 'EMPTY' ELSE country_code_2d
END as country_code_2d FROM country_cnfg_tbl WHERE country_code_2d IN ('CA') OR country_code_2d IS NULL);
你可以重新組織你的問題,因此更有感?也許顯示錶格的圖像? – slugster