【发布时间】:2017-02-09 13:20:37
【问题描述】:
在设置具有动态日期的数据透视表时。在将我的第一个 mysql 查询生成的字符串插入到第二个时,我遇到了逻辑墙。
当我
echo $rowstring
回声生成
SUM( IF( `InvDate`='20160106', round(InvTotalIncl,2), 0 ) ) AS `20160106`,
SUM( IF( `InvDate`='20160107', round(InvTotalIncl,2), 0 ) ) AS `20160107`
通过以下查询测试输出:
select InvOperCode,
SUM( IF( `InvDate`='20160106', round(InvTotalIncl,2), 0 ) )
AS `20160106`,
SUM( IF( `InvDate`='20160107', round(InvTotalIncl,2), 0 ) )
AS `20160107`
FROM `invoice_hdr_tbl`
where InvDate between '20160101' and '20160131'
group by InvOperCode
我得到了我想要的结果。
但是,当我尝试将第一个查询作为字符串传递给第二个查询时
$result = mysql_query("select InvOperCode,'.$rowstring.'
FROM `invoice_hdr_tbl`
where InvDate between '20160101' and '20160131'
group by InvOperCode");
我收到错误“查询以显示表中的字段失败”这是我的代码行,所以我知道我的第二个数据库查询有错误。
if (!$result) {
die("Query to show fields from table failed");
我认为我的字符串转换不正确,或者我的查询的“选择”部分中的变量引用不正确。
任何帮助将不胜感激。
PS 我离开了
echo $rowstring;
在我的代码中识别我正在查看查询并将回显声明为正确的点。无论出于何种原因,它都无法正确传递给我的数据库查询
到目前为止,这是我的代码。
$resultlength = mysql_query("SET SESSION group_concat_max_len = 1000000");
$concatresult = mysql_query("
select group_concat(distinct CONCAT('SUM( IF( `InvDate`=\'',`InvDate`,'\', round(InvTotalIncl,2), 0 ) ) AS `',`InvDate`,'`'))
as Data
FROM `invoice_hdr_tbl`
where InvDate between '20160101' and '20160131'
order by InvDate");
if (!$concatresult) {
die("Query to show fields from table failed");
}
$rowarray = mysql_fetch_assoc($concatresult);
$rowstring = $rowarray['Data'];
echo $rowstring;
$result = mysql_query("select InvOperCode,'.$rowstring.'
FROM `invoice_hdr_tbl`
where InvDate between '20160101' and '20160131'
group by InvOperCode");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Sales Report </h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
【问题讨论】: