I have the following simplified diagram:
CREATE TABLE [file]
(
id UNIQUEIDENTIFIER NOT NULL,
uri NVARCHAR(MAX) NOT NULL,
CONSTRAINT PK_file PRIMARY KEY (id ASC) ON [PRIMARY]
)
CREATE TABLE [property]
(
id UNIQUEIDENTIFIER NOT NULL,
name NVARCHAR(MAX) NOT NULL,
CONSTRAINT PK_property PRIMARY KEY (id ASC) ON [PRIMARY]
)
CREATE TABLE [metadata]
(
fileid UNIQUEIDENTIFIER NOT NULL,
propertyid UNIQUEIDENTIFIER NOT NULL,
value NVARCHAR(MAX) NOT NULL,
CONSTRAINT PK_metadata PRIMARY KEY (fileid, propertyid ASC) ON [PRIMARY]
)
Where [fileid]FKs do [file].[id]and [propertyid]FKs do [property].[id]. Suppose that [properyid]- CLUSTERED, and [value]- NON-CLUSTERED.
I want to select all files matching a specific set of metadata; for example, each file that has a pair of property values size = 1 Kband extension = 'txt'.
In the query that I cited, for example, with the three specified properties, is the following:
SELECT [uri] FROM [file] WHERE [id] IN (
SELECT a.[fileid] FROM (
SELECT COUNT(*) [count], [fileid] FROM [metadata]
WHERE ([propertyid] = '597ddddf-afd2-414f-9774-36f067038064' AND
[value] = N'moo') OR
([propertyid] = 'd83d12de-e4bc-4d18-be12-743504df3318' AND
[value] = N'foo') OR
([propertyid] = 'c00c3966-5034-4818-8567-abd660f37f15' AND
[value] = N'boo')
GROUP BY [fileid]
) a
WHERE a.[count] = 3
)
Can i do better?
source
share