[英]Faster Way to Code this MysQL Query using GROUP BY, HAVING, COUNT, ORDER BY and 2 Tables
I am trying to use this to query 2 tables and get results based on factors from mainly one table. 我试图使用它来查询2个表并基于主要来自一个表的因素获得结果。 I would prefer doing 1 query instead of 1 query with many sub queries in a while or foreach. 我宁愿在一段时间或foreach中使用1个查询代替1个带有许多子查询的查询。
SELECT a.request, a.city
FROM pages a, TNDB_CSV2 b
WHERE a.main_id = b.PerformerID
AND b.PCatID = '3'
AND a.catnum = '303'
AND a.city = b.City
AND b.TicketsYN = 'Y'
AND b.CountryID IN ('38', '217')
GROUP BY b.PerformerID, b.City HAVING COUNT(*) > 4
ORDER BY a.name ASC
So basically what this is saying is that I want to get results in 'pages' where records in 'TNDB_CSV2' have at least 4 matches of 'PerformerID' and 'City'. 因此,基本上这就是我想在“页面”中获得结果,其中“ TNDB_CSV2”中的记录至少具有“ PerformerID”和“ City”的4个匹配项。
The query works correctly, the issue is that it takes between 55-67 seconds to run which is massively way too long. 该查询正常工作,问题是运行需要55-67秒之间的时间,而这太长了。 Similar queries should take a fraction of a second. 类似的查询应该花费一秒钟的时间。 I have never grouped by 2 columns using HAVING and COUNT before so I am thinking there might be a much more efficient way of doing this. 我之前从未使用过HAVING和COUNT按2列进行分组,因此我认为可能会有一种更有效的方法。
The query currently returns 1,011 records and I looked to make sure that the conditions match the results and they do. 该查询当前返回1,011条记录,而我希望确保条件与结果匹配并且确实如此。
Here is your query, formatted with a proper join
clause: 这是您的查询,格式为正确的join
子句:
SELECT a.request, a.city
FROM pages a join
TNDB_CSV2 b
on a.main_id = b.PerformerID and a.city = b.City
WHERE b.PCatID = '3' AND
b.TicketsYN = 'Y' AND
b.CountryID IN ('38', '217') and
a.catnum = '303'
GROUP BY b.PerformerID, b.City
HAVING COUNT(*) > 4
ORDER BY a.name ASC;
You should be able to improve the performance of this query with indexes. 您应该能够使用索引提高此查询的性能。 Here are two that I can think of: 我可以想到以下两个:
pages(catnum, main_id, city, name)
TNDB_CSV2(PerformerID, city, PCatID, TicketsYN, CountryID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.