我遇到一些来自给定结果集的查询的问题我需要在某些条件下从表中选择较少的细节行。
我有三个选择,在联合返回此表之后
SELECT A_ID, B_ID, 1 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 1
UNION
SELECT A_ID, B_ID, 2 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 2
UNION
SELECT A_ID, B_ID, 3 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 3
结果可能是这样的
1000 100 1
1000 200 2
1000 300 3
从该表中,最终结果应为1000 100 1
最好的情况是找到一个值,然后在下次选择时不再搜索。
一些想法?
编辑:
'Jeffrey Kemp'提出的解决方案一个查询工作正常。
1000 100 1
1000 200 2
1000 300 3
1001 200 2
1001 300 3
结果
1000 100 1
1001 200 2
数据库:Oracle数据库10g 10.2.0.4.0版 - 64位生产
答案 0 :(得分:2)
在不知道查询详情的情况下,这是一个需要考虑的选项:
SELECT * FROM (
SELECT * FROM (
SELECT A_ID, B_ID, 1 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 1
UNION
SELECT A_ID, B_ID, 2 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 2
UNION
SELECT A_ID, B_ID, 3 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 3
)
ORDER BY 3
) WHERE ROWNUM = 1;
另一种方法是为查询添加条件以确定它们是否需要运行:
SELECT A_ID, B_ID, 1 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 1
UNION
SELECT A_ID, B_ID, 2 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 2
WHERE NOT EXISTS (SPECIFIC CONDITION FOR LEVEL 1)
UNION
SELECT A_ID, B_ID, 3 FROM MY_TABLE JOIN MY_TABLE2 ON SPECIFIC CONDITION FOR LEVEL 3
WHERE NOT EXISTS (SPECIFIC CONDITION FOR LEVEL 1)
AND NOT EXISTS (SPECIFIC CONDITION FOR LEVEL 2)
当然,我不知道你的“特定条件”的性质,所以我不知道这是否适合你。