2012-03-02 60 views
1

我想将Wordpress数据转换成我自己的数据库,他们的数据库结构给我的问题。这很难解释,所以忍受着我。加入两个表,其中一个有多行

我有两个表如下。他们加入了wp_post.ID = wp_postmeta.post_id

wp_posts 
+----+------------+--------------+ 
| ID | post_title | post_content | 
+----+------------+--------------+ 
| 1 | Game Title | some content | 
+----+------------+--------------+ 

wp_postmeta 
+---------+--------------+------------+ 
| post_id | meta_key  | meta_value | 
+---------+--------------+------------+ 
| 1 | post_type | Review  | 
+---------+--------------+------------+ 
| 1 | game_rating | 8.0  | 
+---------+--------------+------------+ 
| 1 | game_genre | FPS  | 
+---------+--------------+------------+ 

现在我必须为每一个meta_value进入我希望(WHERE meta_value = 'Review'),例如做一个查询。

有没有办法让我运行一个查询并返回post_title,post_content,post_type,gaming_rating和game_genre?

回答

3

看起来你需要做一对夫妇自我加入元表。

;with cte as(
    select pt.post_id, gr.meta_value as game_rating, 
     gg.meta_value as game_genre 
    from wp_postmeta pt 
    inner join wp_postmeta gr 
     on pt.post_id= gr.post_id and 
      gr.meta_key= 'game_rating' 
    inner join wp_postmeta gg 
    on pt.post_id = gg.post_id and 
     gg.meta_key = 'game_genre' 
where pt.meta_key ='post_type' and 
     pt.meta_value ='review' 
) 
select p.post_title, post_content, 
     c.game_rating, c.game_genre 
from wp_post p 
    inner join cte c 
     on c.post_id = p.id 

看到这个小提琴http://sqlfiddle.com/#!3/e7559看到它在行动。

0

这是一种数据透视表;有关如何在MySQL中执行此操作的信息,请参阅this question的答案。

0

你可以做正规内加入

SELECT post_id, post_title, post_content, meta_key, meta_value FROM wp_posts P INNER JOIN wp_postmeta PM ON (P.ID = PM.post_id) ORDER BY post_id 

,然后使用一个简单的脚本来循环直通每个岗位的行。我不知道,如果你使用任何语言来访问数据库,但是在Python(类似于伪代码:P),这将是这样的:

post = {} 

for row in result: 
    first_iteration = 'id' not in post 

    if not first_iteration and row['post_id'] != post['id']: 
     # we have a new post, process it. 

    post['post_title'] = row['post_title'] 
    post['post_content'] = row['post_content'] 
    post[row[meta_key]] = row['meta_key'] 
    post['id'] = row['id'] 


# process the last post