Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate one column to two by row's value

Tags:

mysql

I have 2 tables - posts and meta

posts structure:

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

meta structure:

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

I need to select records where meta.key is "end" or "result", and goup by post.id (if there's both "end" and "result" meta keys)

Here's my try:

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')

It returns two separate records one with meta.key "end" and one with "result".

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

What I need is to merge those two records to one:

+------------+------------+------------+------------+------------+------------+
|    id      |   title    |   post     |   value    |   result   |     end    |
+------------+------------+------------+------------+------------+------------+
|     1      |  Untitled  |      1     |     -      |    88:79   | 1344240000 |
+------------+------------+------------+------------+------------+------------+
like image 222
Gugis Avatar asked Nov 28 '25 16:11

Gugis


1 Answers

You can do this by INNER JOINing meta twice, i.e.

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 fiddle link : http://sqlfiddle.com/#!2/2a89e/5

like image 106
Simon at My School Portal Avatar answered Nov 30 '25 09:11

Simon at My School Portal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!