复杂的SQL查询——查找与多个不同外键匹配的项目
假设您有一个 Products 表 (ID int, Name nvarchar(200))
和另外两个表:ProductsCategories (ProductID int, CategoryID int)
和 发票产品(InvoiceID int,ProductID int)
。
我需要编写一个查询来生成一组与给定的发票 ID 和类别 ID 集相匹配的产品,以便产品列表与所有指定的类别和所有指定的发票相匹配,而无需回退到动态 SQL。想象一下,我需要找到同时属于类别 1 和 2 以及发票 3 和 4 的产品列表。
首先,我编写了一个存储过程,该过程接受类别 id 和发票 id 作为字符串,并解析它们放入表格中:
CREATE PROCEDURE dbo.SearchProducts (@categories varchar(max), @invoices varchar(max))
AS BEGIN
with catids as (select cast([value] as int) from dbo.split(@categories, ' ')),
invoiceids as (select cast([value] as int) from dbo.split(@invoices, ' '))
select * from products --- insert awesomeness here
END
我提出的不同解决方案看起来很糟糕,而且性能更差。我发现的最好的事情是生成一个由所有条件的左连接组成的视图,但这似乎非常昂贵,并且不能解决匹配指定的所有不同键的问题。
更新:这是我编写的示例查询,它产生了预期的结果。我是否错过了任何优化机会?就像忍者的神奇独角兽矩阵运算一样?
with catids as (select distinct cast([value] as int) [value] from dbo.split(@categories, ' ')),
invoiceids as (select distinct cast([value] as int) [value] from dbo.split(@invoices, ' '))
select pc.ProductID from ProductsCategories pc (nolock)
inner join catids c on c.value = pc.CategoryID
group by pc.ProductID
having COUNT(*) = (select COUNT(*) from catids)
intersect
select ip.ProductID from InvoiceProducts ip (nolock)
inner join invoiceids i on i.value = ip.InvoiceID
group by ip.ProductID
having COUNT(*) = (select COUNT(*) from invoiceids)
So imagine that you have a table of Products (ID int, Name nvarchar(200))
, and two other tables, ProductsCategories (ProductID int, CategoryID int)
and InvoiceProducts (InvoiceID int, ProductID int)
.
I need to write a query to produce a set of products that match a given set of invoice ids and category ids such that the list of products match all the specified categories and all the specified invoices, without falling back to dynamic SQL. Imagine I need to find a list of products that are in both categories 1 and 2 and in invoices 3 and 4.
As a start, I've written a stored-procedure that accept the category ids and invoice ids as strings, and parse them into tables:
CREATE PROCEDURE dbo.SearchProducts (@categories varchar(max), @invoices varchar(max))
AS BEGIN
with catids as (select cast([value] as int) from dbo.split(@categories, ' ')),
invoiceids as (select cast([value] as int) from dbo.split(@invoices, ' '))
select * from products --- insert awesomeness here
END
The different solutions I've come up with look awful, and perform worse. The best thing I've found is to generate a view comprised of left joins of all the criteria, but that seems very expensive and doesn't solve the issue of matching all of the different keys specified.
Update: This is an example query I wrote that yields the expected results. Am I missing any optimization opportunities? Like magical unicorn matrix operations by ninjas?
with catids as (select distinct cast([value] as int) [value] from dbo.split(@categories, ' ')),
invoiceids as (select distinct cast([value] as int) [value] from dbo.split(@invoices, ' '))
select pc.ProductID from ProductsCategories pc (nolock)
inner join catids c on c.value = pc.CategoryID
group by pc.ProductID
having COUNT(*) = (select COUNT(*) from catids)
intersect
select ip.ProductID from InvoiceProducts ip (nolock)
inner join invoiceids i on i.value = ip.InvoiceID
group by ip.ProductID
having COUNT(*) = (select COUNT(*) from invoiceids)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
前提是您在
(ProductID, CategoryID)
和(ProductID, InvoiceID)
上都有唯一索引:或者,如果您的值以
CSV
形式传递字符串:请注意,在
SQL Server 2008
中,您可以将表值参数传递到存储过程中。Provided that you have unique indices on both
(ProductID, CategoryID)
and(ProductID, InvoiceID)
:or, if your values are passed in
CSV
strings:Note that in
SQL Server 2008
you can pass table-valued parameters into the stored procedures.我会从类似的事情开始,利用参数中的表格 ID 值。临时表可以帮助提高子查询速度。
I'd start with something like this, utilizing your tabled ID values from the parameters. Temp tables can help with subquery speed.
ProductCategories 应该在 (CategoryId, ProductId) 上有一个聚集索引,InvoiceProducts 应该在 (InvoiceId, ProductId) 上有一个最佳索引。这将允许仅使用聚集索引中的数据来查找给定 CategoryId 和 InvoiceId 的产品 ID。
您可以使用函数返回给定字符串的整数表。谷歌“CsvToInt”并单击来自 SqlTeam 的第一个链接以查看代码。
然后你可以:
ProductCategories should have a clustered index on (CategoryId, ProductId) and InvoiceProducts should have one on (InvoiceId, ProductId) optimally. This will allow finding product ids given the CategoryId and InvoiceId by using the data in the clustered indexes only.
You could use a function to return a table of ints given a string. Google "CsvToInt" and click on the first link from SqlTeam to see the code.
Then you could:
递归 CTE 怎么样?
首先将行号添加到条件表中,然后添加一些伪 SQL(如果愿意):
这将为您提供一种对多个条件执行 AND 的方法,并且应该执行良好。
这有任何意义吗?我最近用 CTE 做了一些非常酷的快速工作,如果需要的话可以详细说明。
删除了 cte 代码,因为它是错误的,并且不值得修复以获得更好的解决方案。
How about a recursive CTE?
First add row numbers to the criteria tables, then some pseudo SQL if you will:
This will give you a way of performing AND on multiple criteria, and should perform well.
Does this make any sense at all? I've done some pretty cool fast stuff with CTEs lately, and can elaborate if necessary.
Removed cte code because it was wrong, and not really worth fixing having a much better solution out there.
将它们作为 XML 参数传递,将它们存储到临时表并连接。
Pass them as XML parameter, store them to a temp table and join.