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 |
+------------+------------+------------+------------+------------+------------+
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With