Hello I need to implement few Queries via dapper on a structure similar to below pseudocode.
// Tags
[{id: 1, name: "Tech"}, {id: 2, name: "SQL"}, {id: 3, name: "C#"}]
// BlogPost [
{
Id: 1
Tags: [1, 2] // Tech, Sql
},
{
Id: 2,
Tags: [1,3] // Tech, C#
},
{
Id: 3,
Tags: [1,2,3] // Text, Sql, C#
}]
Given this query
SELECT
[Blogpost].*
From BlogPost blogPost
LEFT JOIN BlogPostTags tags ON tags.blogId = blogPost.Id
WHERE blogpost.Tags IN (1,2)
Running above query i would expect this result. [{blogId: 1}, {blogId: 2}, {BlogId: 3}]
I need to obtain a result looking like [{blogId: 1}] given the same parameters (1,2) in above query.
Also I need to obtain a result like post [{blogId: 1}, {BlogId: 3}] given the parameters (1,2) in above query.
Does sql (MSSQL) have any nifty way to obtain these result?
Or how could I obtain these result in performant manner as I would have more joins in the actual query?
Thanks!
A "Contains Any" is just a simple
EXISTSquery.For the other two requirements, these are classic Relational Division, one being With Remainder, the other being Without Remainder.
For With Remainder, just do an
EXISTSjoin, along with a groupedHAVINGchecking that all of them exist.For Without Remainder, it's similar, but you need to look for all tags, and then check in the
HAVINGthat the only ones that match are the ones you are looking for.Note that Dapper parameterizes lists as
(@p1, @p2)etc automatically.You can also use a Table Valued Parameter, which is more efficient for large lists.
Define a Table Type, it's best to keep a few useful standard ones around.
Then put the values into a
DataTableand use.AsTableValuedParameter.The query is also slightly different as you would use a join here.