如何在 SQL 中的 Where 子句中使用视图元素
How to use View elements inside Where clause in SQL
我的数据库视图中有这个元素:
CASE
WHEN Type = 'Reserved' THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END AS isReserved,
我想在 WHERE 子句中使用 isReserved 列。我怎样才能做到这一点?谢谢
不能直接做。
要么包含一个子查询。
SELECT *
FROM (SELECT <something> as newAlias FROM YourTable) as T
WHERE T.newAlias = ....
或者只是重复定义
SELECT *
FROM YourTable
WHERE <something> = ....
您可以使用 CROSS APPLY ... VALUES
(在 SQL 服务器中 - 没有注意到它没有为任何特定的 DBMS 标记)
SELECT isReserved
FROM YourTable
CROSS APPLY (VALUES(CASE WHEN Type = 'Reserved' THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT)
END)) CA(isReserved)
WHERE isReserved = 1
但是您最好直接在 WHERE 子句中使用 Type = 'Reserved'
等,而不是引用 CASE 结果。这样它是可搜索的并且可以使用索引。
你可以在where子句中使用相同的表达式,oracle sql不会再次计算它,它会从缓存中获取结果
select CASE
WHEN Type = 'Reserved' THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END AS isReserved
from tablename
where CASE
WHEN Type = 'Reserved' THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END=CAST(0 AS bit)
我的数据库视图中有这个元素:
CASE
WHEN Type = 'Reserved' THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END AS isReserved,
我想在 WHERE 子句中使用 isReserved 列。我怎样才能做到这一点?谢谢
不能直接做。
要么包含一个子查询。
SELECT *
FROM (SELECT <something> as newAlias FROM YourTable) as T
WHERE T.newAlias = ....
或者只是重复定义
SELECT *
FROM YourTable
WHERE <something> = ....
您可以使用 CROSS APPLY ... VALUES
(在 SQL 服务器中 - 没有注意到它没有为任何特定的 DBMS 标记)
SELECT isReserved
FROM YourTable
CROSS APPLY (VALUES(CASE WHEN Type = 'Reserved' THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT)
END)) CA(isReserved)
WHERE isReserved = 1
但是您最好直接在 WHERE 子句中使用 Type = 'Reserved'
等,而不是引用 CASE 结果。这样它是可搜索的并且可以使用索引。
你可以在where子句中使用相同的表达式,oracle sql不会再次计算它,它会从缓存中获取结果
select CASE
WHEN Type = 'Reserved' THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END AS isReserved
from tablename
where CASE
WHEN Type = 'Reserved' THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END=CAST(0 AS bit)