I am getting an error with this in php. What is the correct way to format this string to pass to mysql_query() in php?
SELECT count(*) FROM agents INTO @AgentCount;
SELECT user_agent_parsed, user_agent_original, COUNT( user_agent_parsed ) AS thecount,
COUNT( * ) / ( @AgentCount) AS percentage
FROM agents
GROUP BY user_agent_parsed
ORDER BY thecount DESC LIMIT 50;
In php, here is how I set up the $query
$query = "
SELECT count(*) FROM agents INTO @AgentCount;
SELECT user_agent_parsed, user_agent_original, COUNT( user_agent_parsed ) AS thecount,
COUNT( * ) / ( @AgentCount) AS percentage
FROM agents
GROUP BY user_agent_parsed
ORDER BY thecount DESC LIMIT 50";
That exact query will work fine if I put it directly into MySql via a command line session. Do I need to issue two separate php calls to mysql_query() and store the first result?
I am getting the below error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT user_agent_parsed, user_agent_original, COUNT( user_agent_parsed ) AS thecount' at line 3
The reason for not using a sub select and instead choosing a MySql variable is to avoid a count() happening on every percentage calculation. Though it may be possible the engine is optimizing for that. So far, I have not been able to confirm that. I have also heard sub selects are almost always non optimal.
EXPLAIN tells me this:
id select_type table type possible_keys key key_len ref rows Extra 1 PRIMARY agents index NULL user_agent_parsed 28 NULL 82900 Using temporary; Using filesort 2 SUBQUERY NULL NULL NULL NULL NULL NULL NULL Select tables optimized away