Generating a MYSQL Result

Let's say if we had:

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

To get the data for the message, I would

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

Then swipe through the result set and mysqli_fetch_assoc () each row to give me an associative array with field names in the form of array keys;

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

I would like the actual values ​​to post_keybe the keys of the array, storing the value as post_value. So:

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

Yes, I could format it like this: php and another loop, for example:

$data = [];

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

But I want to know if there is any mysql magic that could save the extra processing required in PHP?


: , , post_key/ . , , , , . , : 1. " ", , . 2, , , , .

+4
2

select, , 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

UPDATE:

- i, , , :

mysql ,

MySQL

:

MySQL PHP-?

, !

+2

. , , , , . , .

0

Source: https://habr.com/ru/post/1608779/


All Articles