0

我在使用 GROUP_CONCAT 并将结果导出到 csv 时遇到问题。

考虑下表
搜索结果
,列搜索 Id | 说明 | 投票 | 搜索类别

and consider the following data in the table
1|java, beans|2|java
2|serialization|3| java
3|jquery| 1|javascript
4|mysql joins|5| database

我需要以下格式的输出

Search Category| description1 | description 2 | votes 1 | votes 2
java           |java,beans    | serialization | 2       | 3
javascript     |jquery         |              | 1
database       | mysqljoins    |              | 5

我需要将此数据输出到 csv 文件中。

我已将以下查询选择类别、GROUP_CONCAT(description)、GROUP_CONCAT(votes) 从 search_results group by search_category 写入以 ',' 结尾的 outfile '/tmp/out.csv' 字段,由 '"' 以 '\n 结尾';

但是,以下是问题 - 上述查询分别返回一列用于描述和投票,其中显示逗号分隔值。我需要为每个值单独列(如所需的输出所示) - 对于 javascript 类别,输出以格式返回

javascript|jquery|5<br/>

我需要 javascript|jquery| 格式的输出 | 5| |

空值应该有一个占位符

4

1 回答 1

0
SELECT
  s1.search_category
  , s1.description AS description1
  , ISNULL(s2.description, '') AS description2
  , s1.votes AS votes1
  , ISNULL(s2.votes, '') AS votes2
FROM search_results AS s1
LEFT OUTER JOIN search_results AS s2 ON s2.search_category = s1.search_category
WHERE s1.search_id < s2.search_id
INTO OUTFILE ...

LEFT JOINing the table to its self will give you the second column if there is one. If there isn't one, the values will be NULL and the ISNULL will return spaces (or whatever else you want).

If there are more than 2 rows with the same search_category, you will get more than one row in the output which might not be what you're after.

于 2012-08-14T13:19:46.573 回答