View返回SELECT

时间:2016-11-21 10:39:59

标签: sql sql-server sql-view

我有一个SQL视图,其返回的结果少于其中的select,我不知道为什么?

SQL视图代码:

SELECT cs.customer_id, cs.store_id, cs.join_date, c.name, c.email, c.phone, cs.points,
       COALESCE (aph.added_point, 0) AS added_point,
       COALESCE (aph.spended_cash, 0) AS spended_cash
FROM dbo.customer_store AS cs 
INNER JOIN dbo.customer AS c
    ON cs.customer_id = c.id 
LEFT OUTER JOIN dbo.added_points_history AS aph
    ON cs.customer_id = aph.customer_id AND cs.store_id = aph.store_id

上面的查询返回26行,但是当我从视图中选择时,它只返回7行!

创建视图的代码:

--Set the options to support indexed views.
SET NUMERIC_ROUNDABORT OFF;
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON;
GO
--Create view with schemabinding.
IF OBJECT_ID ('dbo.customers_store_with_points', 'view') IS NOT NULL
DROP VIEW dbo.customers_store_with_points ;
GO
CREATE VIEW dbo.customers_store_with_points
WITH SCHEMABINDING
AS
SELECT cs.customer_id, cs.store_id, cs.join_date, c.name, c.email, c.phone, cs.points,
    COALESCE (aph.added_point, 0) AS added_point,
    COALESCE (aph.spended_cash, 0) AS spended_cash
FROM dbo.customer_store AS cs 
INNER JOIN dbo.customer AS c
ON cs.customer_id = c.id 
LEFT OUTER JOIN dbo.added_points_history AS aph
ON cs.customer_id = aph.customer_id AND cs.store_id = aph.store_id
GO
--Create an index on the view.
CREATE UNIQUE CLUSTERED INDEX IDX_customerId_storeId
ON dbo.customers_store_with_points (customer_id, store_id);
GO

从视图中获取结果的选择参数:

SELECT TOP 1000 * 
FROM [dbo].[customers_store_with_points]
order by store_id

1 个答案:

答案 0 :(得分:1)

具有相同数据源的相同查询会返回相同的结果 您要么查询不同的数据库,要么查询不同。