跟进我的问题yesterday
我有一个table1
Remark Name Points
----------------------
Cameroon SS 10
Cameroon JL 10
NZ JL 30
我想将其显示为
NZ Cameroon
---------------------
JL 10 10
SS 0 30
备注中table1的条目是动态的,将添加更多条目。
我在Php中尝试的是
$query_get = "SELECT DISTINCT remark FROM table1";
$result = mysql_query($query_get) or die(mysql_error());
$remarks ='';
while ($row = mysql_fetch_array( $result )) {
$remarks .= ",SUM( IF( remark={$row[0]}, 1, 0 ) ) as {$row[0]} ";
};
$query = "SELECT name, .$eventcodes. FROM jr_event_points";
$result1 = mysql_query($query) or die(mysql_error());
现在错误来自查询。一旦我有动态列总结,我应该如何进行第二次查询?
答案 0 :(得分:0)
您可以在MySQL端使用动态SQL
执行此操作SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT('COALESCE(SUM(CASE WHEN remark = ''',
remark,
''' THEN points END), 0) `',
remark,
'`'))
INTO @sql
FROM table1;
SET @sql = CONCAT('SELECT name, ', @sql, ' FROM table1 GROUP BY name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
| NAME | CAMEROON | NZ | |------|----------|----| | JL | 10 | 30 | | SS | 10 | 0 |
这是 SQLFiddle 演示
如果我想通过php来实现它,是否可能?
$sql = "
SELECT GROUP_CONCAT(DISTINCT CONCAT('COALESCE(SUM(CASE WHEN remark = ''',
remark,
''' THEN points END), 0) `',
remark,
'`')) columns
FROM table1";
$result = mysql_query($sql);
if (!$result) {
die ('Error: ' . mysql_error()); //TODO: better error handling
}
$row = mysql_fetch_assoc($result);
$sql = "SELECT name, {$row['columns']} FROM table1 GROUP BY name";
$result = mysql_query($sql);
if (!$result) {
die ('Error: ' . mysql_error()); //TODO: better error handling
}
$row = mysql_fetch_assoc($result);
echo '| '. implode(' | ', array_keys($row)) . ' |' . PHP_EOL;
echo '| '. implode(' | ', array_values($row)) . ' |' . PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo '| '. implode(' | ', array_values($row)) . ' |' . PHP_EOL;
}
输出:
| name | Cameroon | NZ | | JL | 10 | 30 | | SS | 10 | 0 |
注意:考虑从mysql_*
切换到mysqli_*
或PDO
,因为此扩展程序自PHP 5.5.0起已弃用,并将在未来。