开发者

Complicated MySQL Query For Wordpress

Sometimes I think I haven't got the brain power for programming, I just can't get my head round this.

I've got a table called wp_postmeta which looks kind of like this

+-----------+-----------+------------+--------------+
|  meta_id  |  post_id  |  meta_key  |  meta_value  |
+-----------+-----------+------------+--------------+
|    1      |     1     |   type     |   movie      |
+-----------+-----------+------------+--------------+
|    2      |     1     |   name     |  dark knight |
+-----------+-----------+------------+--------------+
|    3      |     2     |    type    |   tv show    |
+-----------+-----------+------------+--------------+
|    4      |     2     |    name    |   lost       |
+-----------+-----------+------------+--------------+
|    5      |     3     |    type    |   tv show    |
+-----------+-----------+------------+--------------+
|    6      |     3     |   name     |  house       |
+-----------+-----------+------------+--------------+
|    7      |     4     |   type     |   movie      |
+-----------+-----------+------------+--------------+
|    8      |     4     |   name     |  godfather   |
+-----------+-----------+------------+--------------+

What I want to do is select the all the movies. I need to find WHERE meta_key = 'type' AND meta_value = 'movie' then get the meta_key "name" where the post_id's match and select the meta_value thus giving me "dark knight" and "godfather".

Sorry for the poor explanation but WordPress doesn开发者_如何学Python't have a logical structure to this part of the database, making it quite hard to explain.


select pm2.meta_value as movie_name
  from wp_postmeta as pm1 join wp_postmeta as pm2
    on pm1.post_id = pm2.post_id
  where pm1.meta_key = 'type' and pm1.meta_value = 'movie' and
    pm2.meta_key = 'name'


SELECT b.meta_value as movie
FROM wp_postmeta a
LEFT JOIN wp_postmeta b ON (a.post_id = b.post_id)
WHERE a.meta_key = 'type'
  AND a.meta_value = 'movie'
  AND b.meta_key = 'name';


Here's a slight variant of Amyam's where the join is implicit. I learnt it this way a long time ago, so it's probably the old fashioned way:

select pm2.meta_value as movie_name
from wp_postmeta pm1, wp_postmeta pm2
where pm1.post_id = pm2.post_id AND
      pm1.meta_key = 'type' AND pm1.meta_value = 'movie' AND
      pm2.meta_key = 'name';


SELECT meta_value FROM wp_postmeta WHERE meta_key = 'name' AND post_id IN
    (SELECT post_id FROM wp_postmeta
    WHERE meta_key  = 'type' AND meta_value = 'movie');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜