Wordpress的复杂MySQL查询

时间:2009-11-01 12:55:09

标签: mysql

有时我觉得我没有掌握编程的脑力,我只是无法理解这一点。

我有一个名为wp_postmeta的表,看起来有点像这样

+-----------+-----------+------------+--------------+
|  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   |
+-----------+-----------+------------+--------------+

我想要做的就是选择所有的电影。我需要找到WHERE meta_key ='type'和meta_value ='movie'然后获取meta_key“name”,其中post_id匹配并选择meta_value,从而给我“黑暗骑士”和“教父”

对于糟糕的解释感到抱歉,但WordPress对数据库的这一部分没有逻辑结构,因此很难解释。

4 个答案:

答案 0 :(得分:3)

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'

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

这是Amyam的一个轻微变体,其中隐含了连接。我很久以前就这样学过它,所以它可能是老式的方式:

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