开发者

Mysql query for using count on a view in php

开发者 https://www.devze.com 2023-02-27 04:21 出处:网络
I have a query: $result = mysql_query(\"CREATE VIEW temporary(IngList) AS ( SELECT DISTINCT (r1.Ingredient)

I have a query:

$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.Ingredi开发者_如何学Goent) 
                       SELECT COUNT(*) FROM temporary");

I want the query to make a view called temporary and have it return a count of the number of rows in the view temporary. I know this code works without the SELECT COUNT(*) because I checked my database and the view is created.

Yet this code throws the 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 COUNT(*) FROM temporary' at line 1

I checked the syntax and it seems to be correct. What seems to be the problem because its quite frustrating.


From the mysql_query documentation:

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

You can't create the view, and select from it in a single mysql_query. The view is unnecessary:

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


For starters you have two statements. What you're writing looks more like a stored procedure. Even if it worked, you would need a semicolon at the end of the first statement. And another statement somewhere saying "DROP VIEW ...." when you are done.

And a temp view is a bit of a non sequitur. I can't find any reference to "CREATE VIEW temporary". Or maybe it's to create a view named temporary with an argument? Views don't take arguments.

I think you might get what you want with a semi-simple SQL statement something like:

$result = 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'");
0

精彩评论

暂无评论...
验证码 换一张
取 消