table: |name|US|IN|SA|CHN|AU|EU|.......
|john|0 |12|2 |0 |1 |0 |.......
|andy|20|17|2 |10 |1 |0 |.......
我有一张包含所有国家/地区的200列的表格。其中包含来自每个国家/地区的点击次数的整数条目。为了在地理图表中显示它们,我想以下列方式解析这些值:
输出:
IN,12
SA,2
AU,1
这样我就排除 0 点击并按用户名 john
分组的国家/地区这是我的方法,但它不完整..
$query = "SELECT * FROM `countries`";
$result = mysql_query("SHOW COLUMNS FROM `countries`.`graph_geo_table` WHERE Field NOT IN ('Name')");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
echo $row[Field];
}
}
答案 0 :(得分:0)
你可以这样做
SELECT column_name country,
CASE column_name
WHEN 'US' THEN us
WHEN 'IN' THEN `in`
WHEN 'SA' THEN sa
WHEN 'CHN' THEN chn
WHEN 'AU' THEN au
WHEN 'EU' THEN eu
END clicks
FROM Table1 t CROSS JOIN
(
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table1'
AND TABLE_SCHEMA = SCHEMA()
AND COLUMN_NAME <> 'name'
) c
WHERE name = 'john'
HAVING clicks > 0
ORDER BY clicks DESC
输出:
| COUNTRY | CLICKS | |---------|--------| | IN | 12 | | SA | 2 | | AU | 1 |
这是 SQLFiddle 演示