我有这样的SQL查询:
SELECT LeftCurrency.LeftCurrency, RightCurrency.RightCurrency FROM
(
SELECT DISTINCT [SecurityData].[Value] AS 'LeftCurrency'
FROM [SecurityData]
JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
WHERE [Fields].[Mnemonic] = 'CRNCY'
) AS LeftCurrency
JOIN
(
SELECT DISTINCT [SecurityData].[Value] AS 'RightCurrency'
FROM [SecurityData]
JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
WHERE [Fields].[Mnemonic] = 'CRNCY'
) AS RightCurrency
ON LeftCurrency.LeftCurrency != RightCurrency.RightCurrency
它运作正常,但我有两个类似的子查询。
我也试过这样的事情:
SELECT * FROM
(
SELECT DISTINCT [SecurityData].[Value] AS 'Currency'
FROM [SecurityData]
JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
WHERE [Fields].[Mnemonic] = 'CRNCY'
) AS leftCurrency, leftCurrency AS rightCurrency
WHERE leftCurrency.Currency != rightCurrency.Currency
但它不起作用。 那么有可能摆脱子查询重复吗?
答案 0 :(得分:1)
在SQLite 3.8.3或更高版本中,您可以使用公用表表达式:
WITH Currency(Currency) AS (
SELECT DISTINCT [SecurityData].[Value]
FROM [SecurityData]
JOIN [Fields] ON [Fields].[Id] = [SecurityData].[FieldId]
WHERE [Fields].[Mnemonic] = 'CRNCY'
)
SELECT LeftCurrency.Currency AS LeftCurrency,
RightCurrency.Currency AS RightCurrency
FROM Currency AS LeftCurrency
JOIN Currency AS RightCurrency ON LeftCurrency.Currency != RightCurrency.Currency
或者,使用临时视图。