2009-10-16 83 views
2

我在php中遇到這個錯誤。格式化該字符串以傳遞給mysql_query()在PHP中的正確方法是什麼?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中,這裏是我如何設置$查詢

 $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通過命令行會話。我是否需要對mysql_query()發出兩個單獨的php調用並存儲第一個結果?

我收到以下錯誤:

您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第3行選擇user_agent_parsed,user_agent_original,COUNT(user_agent_parsed)AS thecount,並使用正確的語法。

不使用子選擇,而是選擇MySql變量是爲了避免在每個百分比計算中發生count()。儘管可能發動機正在爲此進行優化。到目前爲止,我還沒有能夠證實這一點。我也聽說子選擇幾乎總是非最優的。

EXPLAIN告訴我這一點:

 
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。在我的DAL一個典型的功能如下:

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

然後,我有以下幾點:

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_queryentry in the PHP manual頂部的描述:「mysql_query()發送一個唯一的查詢(多個查詢不支持)到當前活動的數據庫...」

至於子查詢,你會感到驚訝;查詢優化器通常會很好地處理它們。