3

我有 2 个表 - 帖子和元

帖子结构:

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

元结构:

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

我需要选择 meta.key 为“end”或“result”的记录,并按 post.id 组合(如果同时存在“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 |
+------------+------------+------------+------------+------------+------------+
4

3 回答 3

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

于 2013-03-27T19:09:08.863 回答
0

由于您正在尝试对数据进行透视,因此您通常会使用带有以下内容的聚合函数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

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

于 2013-03-27T19:05:58.670 回答
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

一个用于测试的 SQLfiddle

于 2013-03-27T19:15:52.347 回答