dsfykqq3403 2014-08-26 07:33
浏览 56

在复杂MySQL查询中使用变量

My MySQL Query is like this :

 $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`"; 

This Query has to return all the values of the column values for two unique countrycodes in two different columns.

Before using the variables. my query was like this, which returned right output.

     $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`
";

But after replacing the real values with the variables the Query didn't work. How can I make the first Query run well ?

  • 写回答

2条回答 默认 最新

  • dongnvwang8591 2014-08-26 07:36
    关注

    Problem is this :

    AS `$countryone`,
    

    when you pass this in SQL query, php would try to search and replace a value for $countryone...so i would suggest to hardcode it as below :

    $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`"; 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥15 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)