从优化的角度来看,我想知道什么时候最好将SELECT
一些任意数据作为列。具体来说,我有这个问题:
SELECT 'String 1' AS segment FROM DUAL
UNION ALL
SELECT 'String 2' AS segment FROM DUAL
UNION ALL
SELECT 'String 3' AS segment FROM DUAL
我需要访问最外层segment
中的SELECT
列,因此我认为只有在必要时才SELECT
,即
SELECT ...,
segment,
CASE WHEN segment = 'String 1' THEN ... END,
...
FROM (
SELECT 'String 1' AS segment FROM DUAL
UNION ALL
SELECT 'String 2' AS segment FROM DUAL
UNION ALL
SELECT 'String 3' AS segment FROM DUAL
),
(
SELECT ...
FROM ...
GROUP BY ...
)
WHERE ...
但是,这比我在最里面的查询中的任意字符串SELECT
更好吗?:
SELECT ...,
segment,
CASE WHEN segment = 'String 1' THEN ... END,
...
FROM (
SELECT ...,
segment
FROM (
SELECT 'String 1' AS segment FROM DUAL
UNION ALL
SELECT 'String 2' AS segment FROM DUAL
UNION ALL
SELECT 'String 3' AS segment FROM DUAL
),
...
GROUP BY ..., segment
)
WHERE ...
由于最外层的查询限制了它从最里面的查询中使用的数据(通过WHERE
),似乎在最里面的查询中选择那些字符串可能会更好,因为之后数据会被削减。是否有关于何时SELECT
这样的数据的最佳实践指南?
编辑基于Example of Data Pivots in SQL (rows to columns and columns to rows)(请参阅标题为“从两行到六行(一列到一行到一行)”的部分:“),我能够将其删除:< / p>
SELECT 'String 1' AS segment FROM DUAL
UNION ALL
SELECT 'String 2' AS segment FROM DUAL
UNION ALL
SELECT 'String 3' AS segment FROM DUAL
相反,我这样做:
SELECT ROWNUM rowno
FROM DUAL
CONNECT BY LEVEL <= 3
然后在我最外面的查询中,我这样做:
CASE WHEN rowno = 1
THEN 'String 1'
WHEN rowno = 2
THEN 'String 2'
WHEN rowno = 3
THEN 'String 3'
END AS segment
但是,这仍然无法解答我在哪里放置SELECT
rowno
{{1}}的最内层或最外层查询的内联视图的问题?
答案 0 :(得分:1)
据我所知,如果你不在你的内部查询中使用rownum,那么你把它放在哪里并不重要,因为优化器只会以最好的方式使用它。这让您决定哪个版本对您更具可读性。