php – MYSQL结果格式化

如果我们有:

tbl `posts`

id | post_type | post_id | post_key | post_value                      | Locale 
------------------------------------------------------------------------------
1  | news      | 1       | title    | The climate in Mongolia         | pl_pl
2  | news      | 1       | content  | Mongolia has strange weather... | pl_pl
3  | news      | 1       | date     | 2015-9-24                       | pl_pl

为了获得帖子的数据,我会

SELECT post_key, post_value 
FROM posts 
WHERE post_id = 1 && post_type = 'news'
AND locale = 'pl_pl'

然后循环遍历结果集和mysqli_fetch_assoc()每一行,给我一个关联数组,字段名称作为数组键;

$row['post_key'] == 'title'; $row['post_value'] == 'The climate in Mongolia';
$row['post_key'] == 'content'; $row['post_value'] == 'Mongolia has strange weather...';

我想要的是post_key的实际值是数组键,保持值为post_value.所以:

$row['title'] == 'The climate in Mongolia'; 
$row['content'] == 'Mongolia has strange weather...'; 

是的我可以使用php和另一个循环来格式化它,例如:

$data = [];

foreach($rows as $r) {
    $data[$r['post_key']] = $r['post_value'];
}

但我想知道是否有一些mysql魔法可以节省PHP所需的额外处理?

关于这个应用程序的更多信息:正如Gal正确指出的那样,我不会根据post_key /传统的表格设计使用字段名称,这似乎很奇怪.但这是一个翻译表,我正在探索有一个表来满足许多其他内容表的翻译的可能性,并且我可以用于新的内容类型,而无需过多地创建多个附加表并维护新字段他们.在这个阶段我不担心性能的原因:1.作为这个启动项目的唯一开发人员以及即时做出决策的人,我相信这将节省时间并立即勾选所有框. 2,与几年时间相比,参赛作品数量较少,我们将有时间寻找解决任何出现的性能问题的方法.

最佳答案 您可以使用这样的选择将所有post_key-> post_value放在一行中:

SELECT
  title,
  MAX(content) AS content,
  MAX(date) AS date
FROM (
  SELECT
    post_type,
    post_id,
    CASE
      WHEN post_key = 'title' THEN
        post_value
    END AS title,
    CASE
      WHEN post_key = 'content' THEN
        post_value
    END AS content,
    CASE
      WHEN post_key = 'date' THEN
        post_value
    END AS date
  FROM
    posts
  WHERE
    post_type = 'news' AND
    post_id = 1
) AS a
GROUP BY
  post_id

http://sqlfiddle.com/#!9/04684/1

更新:

您可以执行类似我公开的操作,但使用列值作为列名称,如下所示:

mysql select dynamic row values as column names, another column as value

MySQL select specific row values as column names

然后调用这样的过程:

How to call a MySQL stored procedure from within PHP code?

希望它能帮到你!

点赞