我正在尝试将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吗?
答案 0 :(得分:3)
看起来你需要在meta表上做几个自联接。
;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以查看其实际效果。
答案 1 :(得分:0)
这是一种支点表;请参阅this question的答案,了解有关如何在MySQL中执行此操作的信息。
答案 2 :(得分: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