Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 慢速存储过程查询_Sql Server - Fatal编程技术网

Sql server 慢速存储过程查询

Sql server 慢速存储过程查询,sql-server,Sql Server,我有桌子 Book: Id | Name | ... UrlRecord: Id | EntityId | Entityname | Slug >> to store id-less url for many other tables like Category | Book | BookChapter... 因此数据是巨大的 EntityId=>在其他表中包含Id,如bookid、categoryid、chapterId Id EntityId Entity

我有桌子

Book: 
Id | Name |  ...

UrlRecord:  
Id | EntityId | Entityname | Slug  >> to store id-less url for many other tables like Category | Book | BookChapter...  
因此数据是巨大的

EntityId=>在其他表中包含Id,如bookid、categoryid、chapterId

Id EntityId    Entityname        Slug
1     2        Category      truyen-tranh
2     2        BookChapter    chapter-one

SearchBookDetails存储过程:

SELECT p.Source,
    (SELECT Slug from UrlRecord url where EntityName = 'Category' and EntityId = (SELECT top(1) CategoryId from Book_Category_Mapping bc where bc.BookId = p.Id)
    ) as CategorySeName

FROM   ....
性能非常慢,如果我有上面的CategorySeName子句,则最长可达22秒,因为这是一个繁重的查询


但是,我不知道如何提高性能,仍然可以像上面那样返回CategorySeName值。

您可以使用EntityId指向N个其他表,如bookid、categoryid、chapterId。
您的表设计错误,实际上无法设置外键。

这是错误的,因为这样就不能强制执行外键。
更糟糕的是,这将导致查询性能降低,因为没有自动创建索引,就像创建外键时一样

因此,查询优化器将提出一个非常难看的执行计划,这解释了为什么它如此缓慢

如果必须具有对象id,则可以创建视图并执行以下操作:

COALESCE(bookid, categoryid, chapterId) AS EntityId 
但我非常怀疑object_id,或者你们所说的EntityId,在这种情况下对你们有任何用处

PS:

比较字符串而不是使用id总是一个坏主意

where EntityName = 'Category'

将这两个反模式结合起来是一个特别好的主意。

您的问题是相关子查询。这是一种非常糟糕的技术,它将您的选择状态更改为一个基本上是光标的状态,并一行一行地运行它。如果你有一个大的数据集,千万不要使用它们。改用派生表、CTE或temp表

您是否尝试获取查询计划?你很可能需要一个索引(EntityId,EntityName)C#与这个问题有什么关系?表上是否有索引,这些索引包含
WHERE
子句中使用的所有列,它们的顺序与
WHERE
子句中使用的顺序相同?像URL记录这样的EAV表是一种设计风格。使用它们是一种糟糕的技术。FKs不会在SQL Server中自动创建索引。它们必须手动创建索引。此表URLCORD仅是一个数据实体,与任何其他表都不相关。事实上,我正在为我的项目使用。