2009-10-16 3 views
2

PHP에서이 오류가 발생합니다. PHP에서 mysql_query()로 전달하기 위해이 문자열을 포맷하는 올바른 방법은 무엇입니까?MySql 변수 및 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; 

PHP에서, 여기에 내가 명령 행 세션을 통해 직접 MySQL의에 넣어 경우 정확한 쿼리가 잘 작동 할 것이라는 $ 쿼리

 $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"; 

을 설정하는 방법입니다. mysql_query()에 두 개의 개별 php 호출을하고 첫 번째 결과를 저장해야합니까?

다음 오류가 발생합니다.

SQL 구문에 오류가 있습니다. mysql 서버 버전에 해당하는 매뉴얼을 확인하여 'user_agent_parsed, user_agent_original, COUNT (user_agent_parsed) count'(COUNT (user_agent_parsed) as the count) 근처의 라인 3에서 사용하십시오.

서브 선택을 사용하지 않고 대신 MySql 변수는 모든 백분율 계산에서 발생하는 count()를 피하는 것입니다. 엔진이이를 최적화 할 수는 있지만 가능할 수도 있습니다. 지금까지, 나는 그것을 확인할 수 없었다. 나는 또한 하위 선택이 거의 항상 비 최적이라고 들었다.

 
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

답변

3

PHP에서는 한 번에 하나의 쿼리 만 사용할 수 있습니다.

$query1 = "SELECT count(*) FROM agents INTO @AgentCount" 
$query2=" 
    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"; 

UPDATE 나는 내 모든 쿼리를 포함하는 DAL 있습니다. 내 BLL (비즈니스 계층)에서 다음

// These functions are reusable public function getAllRows($table) { $sql =" SELECT * FROM $table"; $this->query($sql); return $this->query_result; } 

나는 다음과 같은 한 : 내 DAL의 일반적인 기능은 다음과 같습니다

public function getUserAgents() 
    { 
     $result = parent::getAllRows(); 
     $row = mysql_fetch_array($result); 
     return $row[0]; // Retrieves the first row 

     // Then you take this value and to a second request. Then return the answer/rows. 
    } 
3

당신이 mysql_query를 사용하는 경우는, 다음 네, 별도로 각 쿼리를 보낼 필요가 :

이 나에게 말한다 설명한다. mysql_query의 상단 entry in the PHP manual의 설명에서 : "mysql_query()는 현재 활성화 된 데이터베이스에 고유 쿼리 (여러 쿼리가 지원되지 않음)를 보냅니다 ..."

하위 쿼리의 경우 놀랍습니다. 일반적으로 쿼리 최적화 프로그램은이를 매우 잘 처리합니다.