0
$query = mysql_query(" SET @c1=0; SELECT @c1 := @c1+1 as Week,
AVG(Temp) AS Average_Temperature FROM (   SELECT t1.*, COUNT(*) cnt
FROM test2 t1   LEFT JOIN test2 t2
ON t2.Date <= t1.Date
AND YEAR(FROM_UNIXTIME(t2.Date)) = YEAR(FROM_UNIXTIME(t1.Date))
AND MONTH(FROM_UNIXTIME(t2.Date)) = MONTH(FROM_UNIXTIME(t1.Date))   GROUP 
BY Date ) t GROUP BY   YEAR(FROM_UNIXTIME(Date)), MONTH(FROM_UNIXTIME(Date)), CEIL(cnt/7);" );

If I dont use SET @c1=0; I got no error... So whats the use of this on json php? Above code successfully queried on PHPMyAdmin.

edit: solved

3
  • You cannot execute two SQL sentences in mysql_query Commented Dec 28, 2013 at 15:04
  • I just want to get row count on the current table but others fail.. Only this one is good for me.. what can I do? Commented Dec 28, 2013 at 15:07
  • Why don't you do it in PHP? Run the select query, iterate the result set and count... Commented Dec 28, 2013 at 15:11

2 Answers 2

1

Just enclose them in quotes .. See here $query = mysql_query(" your query ");

Like this..

$query = mysql_query("
    SELECT AVG(Temp) AS Average_Temperature FROM (
    SELECT t1.*, COUNT(*) cnt FROM test2 t1
  LEFT JOIN test2 t2
    ON t2.Date <= t1.Date
    AND YEAR(FROM_UNIXTIME(t2.Date)) = YEAR(FROM_UNIXTIME(t1.Date))
        AND MONTH(FROM_UNIXTIME(t2.Date)) = MONTH(FROM_UNIXTIME(t1.Date))
  GROUP 
    BY Date
) t
GROUP BY
  YEAR(FROM_UNIXTIME(Date)), MONTH(FROM_UNIXTIME(Date)), CEIL(cnt/7);
");

Disclaimer : Stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.

Sign up to request clarification or add additional context in comments.

1 Comment

oh! I forgot it! Thanks it works now.. Its easy to forget this things in a mess like that :)
0

Clearly, the set and select are incompatible as a single query. There is an easy work-around. Set the variable in the query:

SELECT @c1 := @c1+1 as Week, AVG(Temp) AS Average_Temperature
FROM (SELECT t1.*, COUNT(*) as cnt
      FROM test2 t1 LEFT JOIN
           test2 t2
           ON t2.Date <= t1.Date AND
              YEAR(FROM_UNIXTIME(t2.Date)) = YEAR(FROM_UNIXTIME(t1.Date)) AND
              MONTH(FROM_UNIXTIME(t2.Date)) = MONTH(FROM_UNIXTIME(t1.Date))
      GROUP BY Date
     ) t cross join
     (select @c1 := 0) const
GROUP BY YEAR(FROM_UNIXTIME(Date)), MONTH(FROM_UNIXTIME(Date)), CEIL(cnt/7);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.