2011-04-18 153 views
0

觀看計數我有一個查詢:MySQL查詢使用在PHP

$result = mysql_query("CREATE VIEW temporary(IngList) AS (
         SELECT DISTINCT (r1.Ingredient) 
          FROM recipes r1, 
           recipes r2 
          WHERE r1.Country = '$temp' 
          AND r2.Country = '$temp2' 
          AND r1.Ingredient = r2.Ingredient) 
         SELECT COUNT(*) FROM temporary"); 

我想查詢做出視圖稱爲暫時性的,有它在視圖中暫時返回的行數的計數。我知道這段代碼沒有SELECT COUNT(*),因爲我檢查了我的數據庫並創建了視圖。

然而,這個代碼拋出的錯誤:

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 COUNT(*) FROM temporary' at line 1

我檢查語法,它似乎是正確的。什麼似乎是問題,因爲它相當令人沮喪。

回答

0

mysql_query documentation

mysql_query() sends a unique query (multiple queries are not supported)...

你不能創建視圖,並從一個mysql_query中選擇它。視圖是不必要的:

$sql = sprintf("SELECT COUNT(DISTINCT r1.Ingredient) 
        FROM recipes r1 
       WHERE r.country = '%s' 
        AND EXISTS(SELECT NULL 
           FROM recipes r2 
           WHERE r2.Country = '%s' 
           AND r1.Ingredient = r2.Ingredient)", 
       $temp, $temp2); 

$result = mysql_query($sql); 
0

對於初學者,你有兩個陳述。你寫的東西看起來更像是一個存儲過程。即使它起作用,在第一個語句結尾處也需要分號。當你完成時,另一個聲明說「DROP VIEW ....」。

而臨時視圖有點不合適。我找不到任何對「臨時創建視圖」的引用。或者也許是用參數創建一個名爲臨時的視圖?觀點不需要論證。

我想你可能會得到你想要半簡單的SQL語句是這樣的:

$結果= mysql_query(

"SELECT COUNT(DISTINCT r1.Ingredient) 
FROM recipes r1 
JOIN recipes r2 ON r1.Ingredient = r2.Ingredient 
WHERE r1.Country = '$temp' 
    AND r2.Country = '$temp2'");