在复杂MySQL查询中使用变量

时间:2014-08-26 07:33:20

标签: php mysql sql

我的MySQL查询是这样的:

 $myquery= "`SELECT  `year`, 

        sum(case when `countrycode` = '$countryone' then `values` else 0 end) AS `$countryone`,
        sum(case when `countrycode` = '$countrytwo' then `values` else 0 end) AS `$countrytwo`

FROM   `$index`
GROUP BY `year`"; 

此查询必须返回两个不同列中两个唯一国家/地区代码的列值的所有值。

使用变量之前。我的查询是这样的,它返回正确的输出。

     $myquery = "SELECT  `year`, 

        sum(case when `countrycode` = 'NPL' then `values` else 0 end) AS `NPL`,
        sum(case when `countrycode` = 'USA' then `values` else 0 end) AS `USA`

FROM   `gainfinal`
GROUP BY `year`
";

但是在用变量替换实际值之后,Query不起作用。如何让第一个Query运行良好?

2 个答案:

答案 0 :(得分:1)

问题是:

AS `$countryone`,

在SQL查询中传递此内容时,php会尝试搜索并替换$countryone的值...所以我建议将其硬编码如下:

$myquery= "`SELECT  `year`, 
        sum(case when `countrycode` = '$countryone' then `values` else 0 end) AS $countryone, /* notice "`" is removed */
        sum(case when `countrycode` = '$countrytwo' then `values` else 0 end) AS $countrytwo  /* notice "`" is removed */
FROM   `$index`
GROUP BY `year`"; 

答案 1 :(得分:1)

在查询中使用 - '".$countryone."'代替'$countryone',因为它将被视为字符串。