Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated MySQL Query

I'm creating a site in wordpress which holds information on television programs. I'm using custom fields to select each post.

The table looks something like this

+----+---------+----------+------------+
| id | post_id | meta_key | meta_value |
+----+---------+----------+------------+
| 1  |    1    |   name   | Smallville |
| 2  |    1    |  season  |     1      |
| 3  |    1    |  episode |     1      |
| 4  |    2    |   name   | Smallville |
| 5  |    2    |  season  |     1      |
| 6  |    2    |  episode |     2      |
+----+---------+----------+------------+

Basically what I need to do is select all of the tv shows with the name "Smallville" and sort them by season then by episodes. I thought it would be fairly simple but everything I have tried returns nothing.

Could you please explain how I can do this?

like image 587
Ben Shelock Avatar asked Nov 29 '22 11:11

Ben Shelock


1 Answers

You can do something like this:

SELECT 
    t1.post_id, 
    t1.meta_value AS name, 
    t2.meta_value AS season, 
    t3.meta_value AS episode
FROM
    (
    SELECT *
    FROM the_table
    WHERE meta_key = 'name'
    ) t1
INNER JOIN
    (
    SELECT *
    FROM the_table
    WHERE meta_key = 'season'
    ) t2 ON t1.post_id = t2.post_id
INNER JOIN
    (
    SELECT *
    FROM the_table
    WHERE meta_key = 'episode'
    ) t3 ON t1.post_id = t3.post_id

This will give you the result:

| post_id | name       | season | episode |
-------------------------------------------
|    1    | Smallville | 1      | 1       |
|    2    | Smallville | 1      | 2       |

In this form it is much easier for any operations.

What you need is to add:

WHERE name = 'Smallville'
ORDER BY season, episode
like image 200
Lukasz Lysik Avatar answered Dec 06 '22 03:12

Lukasz Lysik