按行的值分隔一列到两列

时间:2013-03-27 19:00:30

标签: mysql

我有2个表 - 帖子和元

帖子结构:

+---------+---------+
|   id    |  title  |
+---------+---------+

元结构:

+---------+---------+---------+
|   post  |   key   |  value  |
+---------+---------+---------+

我需要选择meta.key为“end”或“result”的记录,并通过post.id选择goup(如果有“end”和“result”元键的话)

这是我的尝试:

SELECT
posts.id,
posts.title,
meta.post,
meta.`value`,
CASE meta.`key` WHEN 'result' THEN value END AS 'result',
CASE meta.`key` WHEN 'end' THEN value END AS 'end'
FROM
posts
INNER JOIN meta ON posts.id = meta.post
WHERE meta.`key` IN ('result', 'end')

它返回两个单独的记录,一个是meta.key“end”,另一个是“result”。

+------------+------------+------------+------------+------------+------------+
|    id      |   title    |   post     |   value    |   result   |     end    |
+------------+------------+------------+------------+------------+------------+
|     1      |  Untitled  |      1     |     5      |    (Null)  | 1344240000 |
+------------+------------+------------+------------+------------+------------+
|     1      |  Untitled  |      1     |   88:79    |    88:79   |   (Null)   |
+------------+------------+------------+------------+------------+------------+

我需要的是将这两个记录合并为一个:

+------------+------------+------------+------------+------------+------------+
|    id      |   title    |   post     |   value    |   result   |     end    |
+------------+------------+------------+------------+------------+------------+
|     1      |  Untitled  |      1     |     -      |    88:79   | 1344240000 |
+------------+------------+------------+------------+------------+------------+

3 个答案:

答案 0 :(得分:1)

你可以通过两次INNER JOINing meta来做到这一点,即

SELECT

  p.id,
  p.title,
  mr.value AS result,
  me.value AS end

FROM posts AS p

INNER JOIN meta AS mr

  ON mr.post = p.id
  AND mr.`key` = 'result'

INNER JOIN meta AS me
  ON me.post = p.id
  AND me.`key` = 'end';

SQL小提琴链接:http://sqlfiddle.com/#!2/2a89e/5

答案 1 :(得分:0)

由于您尝试 pivot 数据,因此通常会使用CASE的聚合函数:

SELECT
  posts.id,
  posts.title,
  -- meta.post,
  -- meta.`value`,
  max(CASE meta.`key` WHEN 'result' THEN value END) AS 'result',
  max(CASE meta.`key` WHEN 'end' THEN value END) AS 'end'
FROM posts
INNER JOIN meta 
  ON posts.id = meta.post
WHERE meta.`key` IN ('result', 'end')
GROUP BY posts.id, posts.title  -- , meta.post, meta.`value`

请参阅SQL Fiddle with Demo

注意:您为value列显示了两个单独的值,您需要决定选择值的逻辑,因为如果执行group by时它们是不同的,您将获得多行。因此,您会看到我已注释掉这两列,因为它们已在CASE中使用,并且已显示post列。

答案 2 :(得分:0)

只要“结果”只有一行,每个帖子ID只有一行“结束”,您可以使用MAX作为原始查询的聚合函数,最后使用posts.id进行分组;我无法弄明白你VALUE的逻辑,所以我暂时把它遗弃了;

SELECT posts.id, posts.title,
  MAX(CASE meta.`key` WHEN 'result' THEN value END) AS 'result',
  MAX(CASE meta.`key` WHEN 'end' THEN value END)  AS 'end'
FROM posts
INNER JOIN meta ON posts.id = meta.post
WHERE meta.`key` IN ('result', 'end')
GROUP BY posts.id, posts.title

An SQLfiddle to test with