[英]Select MAX() of Multiple Columns in MySQL
I currently have a massive query (using PHP and MySQL) and I'm not sure how to optimize it in order to reduce its massive load of 18-25 seconds. 我目前有一个庞大的查询(使用PHP和MySQL),但不确定如何优化它以减少18-25秒的庞大负载。 I've looked at previous answers and have found that they all sort of write a similarly large amount of code resulting in a similar script execution time and so I'd like to see if anyone would have any alternative ideas as opposed to the ones already posed: 我查看了以前的答案,发现它们都编写了大量类似的代码,从而导致相似的脚本执行时间,因此,我想看看是否有人会提出替代方案,而不是已经提出的方案构成:
TLDR; TLDR; I need to select the maximum column for each analytics ID and this takes on a massive load and so i need to reduce it somehow 我需要为每个分析ID选择最大列,这会承受巨大的负担,因此我需要以某种方式减少它
$qry = "SELECT DISTINCT ip,country_code,country,
(SELECT MAX(region) FROM analytics RegOne WHERE bid='$id' AND RegOne.ip= IPOne.ip) AS region,
(SELECT MAX(city) FROM analytics CitOne WHERE bid='$id' AND CitOne.ip= IPOne.ip) AS city,
(SELECT MAX(os) FROM analytics OSOne WHERE bid='$id' AND OSOne.ip= IPOne.ip) AS os,
(SELECT MIN(browser) FROM analytics BroOne WHERE bid='$id' AND BroOne.ip= IPOne.ip) AS browser,
(SELECT MIN(resolution) FROM analytics ResOne WHERE bid='$id' AND ResOne.ip= IPOne.ip) AS resolution,
(SELECT MAX(timestamp) FROM analytics DateOne WHERE bid='$id' AND DateOne.ip= IPOne.ip) AS LatestDate
FROM analytics AS IPOne
WHERE bid='$id'
ORDER BY LatestDate DESC
LIMIT 15 OFFSET $offset";
This is taking data from a massive table and so i don't expect it to take 0 seconds however any time reduction would be fine rather than ~21 seconds. 这是从一个巨大的表中获取数据,因此我不希望它花费0秒,但是任何时间减少都是可以的,而不是大约21秒。
Why not 为什么不
SELECT ip, country_code, country,
MAX(region) as region,
MAX...
MAX(timestamp) as LatestDate
FROM analytics
WHERE bid = '$id'
GROUP BY ip, country_code, country
ORDER BY LatestDate DESC
LIMIT 15 OFFSET $offset";
You should have some index starting with bid
. 您应该有一些以bid
开头的索引。 This might be better: 这可能更好:
INDEX(bid, ip, country_code, country)
You should have a composite KEY on (bid, ip)
. 您应该在(bid, ip)
上有一个复合键。 If you have KEY on (bid)
then add (or replace it with) (bid, ip)
如果您在(bid)
上有KEY,则添加(或替换为) (bid, ip)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.