我写了下面的查询,它在Mysql工作台中完美运行。但是当我从php运行它时,它会抛出错误。任何帮助,将不胜感激。
QUERY:
$sql=SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT('max(CASE WHEN date = "',date,'" THEN Market_cap end) AS "',date,'"'))
INTO @sql
FROM company_name
JOIN master on company_name.id=master.company_id
where date between '2018-01-01' and '2018-01-02';
SET @sql = CONCAT('SELECT name,symbol,',@sql,'FROM company_name join master on company_name.id=master.company_id where date between ''2018-01-01'' and ''2018-01-02''GROUP BY name,symbol');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
$res=mysqli_query($conn,$sql);
if (!$res) {
echo("Error description: " . mysqli_error($conn));
}
图片中显示的错误:
另外我必须使用上面的查询添加我的输出:
答案 0 :(得分:0)
试试这个
$sql="SET @sql = NULL;SELECT GROUP_CONCAT(DISTINCT CONCAT('max(CASE WHEN date = '".$date."' THEN Market_cap end) AS '".$date."'))INTO @sql FROM company_name join master on company_name.id=master.company_id where date between '2018-01-01' and '2018-01-02';SET @sql = CONCAT('SELECT name,symbol,',@sql,'FROM company_name join master on company_name.id=master.company_id where date between ''2018-01-01'' and ''2018-01-02''GROUP BY name,symbol');PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt";
$res= mysqli_query($conn,$sql);if (!$res) {echo("Error description: " . mysqli_error({$conn}));
注意:我不确定您为什么在查询中使用
"',date,'"
,所以 将其替换为'".$date."'
。请务必根据需要使用它。