【发布时间】:2017-03-20 14:01:21
【问题描述】:
我必须创建一个动态搜索。搜索条件存储在表中,存储记录有一个主表。这是结构:
--Main Table. This table stores records of a user. Basically we store files in this table. Each file is associated with a single city.
DECLARE @Records TABLE(
[RecordId] INT IDENTITY(1,1),
[FileName] VARCHAR(100),
[OwnerId] INT,
[CityId] INT
)
INSERT INTO @Records
SELECT 'A', 100, 101 UNION
SELECT 'B', 100, 102 UNION
SELECT 'C', 100, 103 UNION
SELECT 'D', 100, 104
--The next table is used to associate a file with multiple friends.
DECLARE @FriendRecords TABLE
(
[Id] INT IDENTITY(1,1),
[RecordId] INT,
[FriendId] INT
)
INSERT INTO @FriendRecords
SELECT 1, 201 UNION --File '1' is associated with 'FriendId' 201
SELECT 1, 202 UNION --File '1' is associated with 'FriendId' 202
SELECT 2, 201 UNION --File '2' is associated with 'FriendId' 201
SELECT 3, 202 --File '3' is associated with 'FriendId' 202
--The following table is used to create a criteria for user.
DECLARE @Criteria TABLE
(
[CriteriaId] INT IDENTITY(1,1),
[CriteriaName] VARCHAR(50),
[OwnerId] INT
)
INSERT INTO @Criteria
SELECT 'SampleCriteria', 100 --Criteria created by user 100
--The following table is used to store cities that needs to be searched in 'Records' table for owner of criteriaId '1'.
DECLARE @CriteriaCities TABLE(
[CriteriaCityId] INT IDENTITY(1,1),
[CriteriaId] INT,
[CityId] INT
)
INSERT INTO @CriteriaCities
SELECT 1, 101 UNION
SELECT 1, 102 UNION
SELECT 1, 103
--The following table is used to store friend that needs to be searched in 'FriendsRecords' table for owner of criteriaId '1'.
DECLARE @CriteriaFriend TABLE(
[CriteriaCityId] INT IDENTITY(1,1),
[CriteriaId] INT,
[FriendId] INT
)
INSERT INTO @CriteriaFriend
SELECT 1, 202;
基本上,用户可以创建一个条件(@Criteria 表)并存储搜索参数(@CriteriaCities 和@CriteriaFriend 表)。要求是根据存储的条件获取文件。我正在寻找的查询应该从@Records 表中返回具有cityIds 101、102&103 AND FriendId '201' 的记录。结果只是@Records 表中的“C”。如果我在所有表上创建左连接,我也会获得 ownerId '100' 的其他记录。如果我在表中包含一个内部联接,如果@CriteriaCities 或@CriteriaFriend 表中没有条件条目,我将不会得到任何记录。根据链接表(@CriteriaCities,@CriteriaFriend)中存在的记录搜索主表中记录的查询应该是什么?如果搜索参数未存储在这些表中,则不应在这些表之间创建连接。
【问题讨论】:
-
为什么会有这么复杂的过程?这种设计的原因是什么?此外,在您的示例中,如果您正在搜索
101、102或103的CityID和201的FriendID,则不匹配文件A和BC的?即使您根据脚本使用FriendID或202。你会匹配A和C。您如何将 FileC作为输出?
标签: sql-server tsql sql-server-2012