titans
titans

Reputation: 451

subquery does not work on php

I have table. I need in my query count some field. This is my query:

select COUNT(q1) as 'result'
from (select DISTINCT id_qs as 'q1' FROM main where id_exam=40) as q2

It's query perfect work. But. When I put it in php code:

   function HowManyQuestion($id)
   {
        mysql_connect($this->hostname,$this->username,$this->password) OR DIE("Can't connect");
        mysql_select_db($this->dbName) or die(mysql_error());
        $query = "select COUNT(q1) as 'result' from (select DISTINCT id_qs as 'q1' FROM main where id_exam=40) as q2;";
        $res = mysql_query($query) or die(mysql_error());
        $id=0;
        while ($row=mysql_fetch_array($res)) {
            $id=$row['result'];
            break;
        }
        return $id;

   }

In result I have 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 ') as q2' at line 1

So how this fix?

Upvotes: 0

Views: 110

Answers (2)

alok.kumar
alok.kumar

Reputation: 380

Alias column name can't be used for further processing

            select COUNT(id_qs) as 'result'
                   from (select DISTINCT id_qs as 'q1' FROM main where id_exam=40) as q2

Upvotes: 0

John Woo
John Woo

Reputation: 263723

Actually you can simplify the query without using subquery, and which I think will remove the error.

SELECT COUNT(DISTINCT id_qs) totalCount
FROM main
WHERE id_exam = 40

Upvotes: 5

Related Questions