/*筛选索引 SQL SERVER 2008 测试*/
/*
应用:用户表,通过ID可以登录,
如果有电话号码也可以登录,但此时必须保证电话号码唯一。
*/
--1,创建测试表
CREATE TABLE T
(
ID VARCHAR(20) NOT NULL PRIMARY KEY,
MOBILE VARCHAR(20)NULL
)
--2,创建索引 唯一,非聚集索引(并添加筛选条件)
CREATE UNIQUE NONCLUSTERED INDEX [IDX_MOBILE] ON [dbo].[T]
(
[MOBILE] ASC
)
WHERE ([MOBILE] IS NOT NULL)
DROP INDEX [IDX_MOBILE] on t
INSERT INTO T SELECT ‘A‘,NULL
INSERT INTO T SELECT ‘B‘,NULL
INSERT INTO T SELECT ‘C‘,‘A‘
INSERT INTO T SELECT ‘D‘,‘D‘
INSERT INTO T SELECT ‘E‘,‘B‘
INSERT INTO T SELECT ‘F‘,‘C‘
INSERT INTO T SELECT ‘G‘,NULL
INSERT INTO T SELECT ‘H‘,NULL
SELECT * FROM T
/*mysql创建唯一索引,null值直接被忽略*/
create table t
(
id varchar(20) not null PRIMARY key,
mobile varchar(20) null
)
select * from t
INSERT INTO t (id,mobile) VALUES( ‘A‘,NULL);
INSERT INTO t (id,mobile) VALUES(‘B‘,NULL);
INSERT INTO t (id,mobile) VALUES( ‘C‘,‘A‘);
INSERT INTO t (id,mobile) VALUES( ‘D‘,‘D‘);
INSERT INTO t (id,mobile) VALUES( ‘E‘,‘B‘);
INSERT INTO t (id,mobile) VALUES( ‘F‘,‘C‘);
INSERT INTO t (id,mobile) VALUES( ‘G‘,‘‘);
INSERT INTO t (id,mobile) VALUES( ‘H‘,‘‘);
truncate table t
--2,创建索引 唯一
CREATE UNIQUE INDEX IDX_MOBILE ON t
(
mobile ASC
)
原文:http://www.cnblogs.com/wtujedp/p/4647672.html