Why does this SQL query kill my server?
-
25-10-2019 - |
문제
When I run this query on SQL server from a Varnish cache server.
select count(distinct email) from aiki_users, ocal_files where userid =
(select upload_user from ocal_files where upload_user = userid limit 1)
With aiki_users
table having > 80000 rows
and the ocal_files
table having > 30000 rows.
It kills the server. It is called from a php script via ajax. I have to close the page that calls it.
I don't know what it returns, but I know that the thing I want to do should be created with group by and having, but I don't know how.
The aiki_users table looks like this:
CREATE TABLE IF NOT EXISTS `aiki_users` (
`userid` int(9) unsigned NOT NULL auto_increment,
`username` varchar(100) NOT NULL default '',
`full_name` varchar(255) NOT NULL,
`country` varchar(255) NOT NULL,
`sex` varchar(25) NOT NULL,
`job` varchar(255) NOT NULL,
`password` varchar(100) NOT NULL default '',
`oauth_passcode` varchar(255) NOT NULL,
`oauth_token` varchar(255) NOT NULL,
`oauth_token_secret` varchar(255) NOT NULL,
`usergroup` int(10) NOT NULL default '0',
`email` varchar(100) NOT NULL default '',
`avatar` varchar(255) NOT NULL,
`homepage` varchar(100) NOT NULL default '',
`first_ip` varchar(40) NOT NULL default '0',
`first_login` datetime NOT NULL,
`last_login` datetime NOT NULL,
`last_ip` varchar(40) NOT NULL,
`user_permissions` text NOT NULL,
`maillist` int(1) NOT NULL,
`logins_number` int(11) NOT NULL,
`randkey` varchar(255) NOT NULL,
`is_active` int(5) NOT NULL,
PRIMARY KEY (`userid`),
KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
I don't have correct access to the server, I can't see the defnition of ocal_files but:
ocal_files.aiki_users = aiki_users.userid
Can anybody tell me how bad the query is and what it returns?
해결책
You're selecting from both aiki_user and ocal_files in the main query, without specifying a join clause, the where in the nested query isn't going to stop the full table join...
다른 팁
I'd recommend running EXPLAIN PLAN on both queries and seeing what the database tells you.
My guess is that you have to do a TABLE SCAN, so the performance is terrible.