Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL query for finding rows that match a set of properties

I have got the following simplified schema:

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 to [file].[id] and [propertyid] FKs to [property].[id]. Assume that [properyid] is CLUSTERED and [value] is a NON-CLUSTERED.

I want to select all of the files that match a certain set of metadata; for example every file that has a property value pair of size = 1 Kb and extension = 'txt'.

The query that I've come up with, for example with three properties specified, is this:

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 any better?

like image 826
satnhak Avatar asked Apr 22 '11 08:04

satnhak


Video Answer


2 Answers

;WITH propertylist AS (
  SELECT propertyid = '597ddddf-afd2-414f-9774-36f067038064', value = N'moo' UNION ALL
  SELECT propertyid = 'd83d12de-e4bc-4d18-be12-743504df3318', value = N'foo' UNION ALL
  SELECT propertyid = 'c00c3966-5034-4818-8567-abd660f37f15', value = N'boo'
)
SELECT uri
FROM file
WHERE id IN (
  SELECT m.fileid
  FROM metadata m
    INNER JOIN propertylist p ON m.propertyid = p.propertyid AND m.value = p.value
  GROUP BY m.fileid
  HAVING COUNT(*) = (SELECT COUNT(*) FROM propertylist)
)
like image 58
Andriy M Avatar answered Oct 19 '22 23:10

Andriy M


Maybe something like this?

SELECT 
   [uri] 
FROM 
   [file] 
WHERE 
   EXISTS(
        SELECT 
           NULL
        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') AND 
              [File].[id] = [metadata].[fileid]
        GROUP BY 
           [fileid]
        HAVING 
           COUNT(*) = 3
       )
like image 33
Magnus Avatar answered Oct 19 '22 23:10

Magnus