简体   繁体   English

返回查询结果的相关记录数

[英]Return number of related records for the results of a query

I have 2 related tables, Tapes & Titles related through the Fields TapeID Tapes.TapeID & Titles.TapeID 我有两个相关的表,磁带和标题通过Fields TapeID Tapes.TapeID和Titles.TapeID相关

I want to be able to query the Tapes Table on the Column Artist and then return the number of titles for each of the matching Artist records 我希望能够查询Column Artist上的Tapes Table,然后返回每个匹配的Artist记录的标题数

My Query is as follows 我的查询如下

SELECT Tapes.Artist,COUNT(Titles.TapeID) 
FROM Tapes 
INNER JOIN Titles on Titles.TapeID=Tapes.TapeID 
GROUP BY Tapes.Artist 
HAVING TAPES.Artist LIKE <ArtistName%>"

The query appears to run then seems to go into an indefinite loop I get no syntax errors and no results 查询似乎运行然后似乎进入一个无限循环我没有语法错误,没有结果

Please point out the error in my query 请在我的查询中指出错误

Here are two likely culprits for this poor performance. 以下是这种糟糕表现的两个可能罪魁祸首。 The first would be the lack of index on Tapes.TapeId . 第一个是Tapes.TapeId上缺少索引。 Based on the naming, I would expect this to be the primary key on the Tapes table. 基于命名,我希望这是Tapes表上的主键。 If there are no indexes, then you could get poor performance. 如果没有索引,则可能会导致性能不佳。

The second would involve the selectivity of the having clause. 第二个涉及having子句的选择性。 As written, MySQL is going to aggregate all the data for the group by and then filter out the groups. 如上所述,MySQL将聚合该group by 所有数据,然后过滤掉这些组。 In many cases, this would not make much of a difference. 在许多情况下,这不会产生太大的影响。 But, if you have lots of data and the condition is selective (meaning few rows match), then moving it to a where clause would make a difference. 但是,如果你有大量的数据并且条件是选择性的(意味着几行匹配),那么将它移动到where子句会产生影响。

There are definitely other possibilities. 肯定有其他可能性。 For instance, the server could be processing other queries. 例如,服务器可能正在处理其他查询。 An update query could be locking one of the tables. 更新查询可以锁定其中一个表。 Or, the columns TapeId could have different types in the two tables. 或者, TapeId列可以在两个表中具有不同的类型。

You can modify your question to include the definition of the two tables. 您可以修改您的问题以包含两个表的定义。 Also, put explain before the query and include the output in the question. 另外,在查询之前放置explain并在问题中包含输出。 This indicates the execution plan chosen by MySQL. 这表示MySQL选择的执行计划。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM