我有两张桌子:
_____________________________
| wp_post | wp_postmeta |
|______________|_____________|
| ID | meta_id |
| post_title | post_id |
| post_content | meta_key |
| guid | meta_value |
|______________|_____________|
wp_postmeta
表包含以下行:
| meta_id | post_id | meta_key | meta_value
|---------|---------|-----------------|---------------
| 310 | 156 | level | Blue
| 311 | 156 |_post_main_intro | Some text
我想要的结果是:
post_title, post_content, meta_value as color, meta_value as main_intro
我尝试了不同的连接,但我无法解决它。
这就像我得到的那样:
SELECT a.post_title, b.meta_key, b.meta_value
FROM wp_posts a
LEFT JOIN wp_postmeta b ON a.ID = b.post_id
WHERE b.meta_key = 'level'
但这不允许我提取_post_main_intro
数据。
如果有人能把我推向正确的方向,我会很高兴:)
更新
我目前的解决方案就是这个(并且有效)
SELECT a.id, a.post_title, b.meta_value as color, c.meta_value as post_intro
FROM wp_posts a
LEFT JOIN wp_postmeta b ON a.ID = b.post_id
LEFT JOIN wp_postmeta c ON a.ID = c.post_id
WHERE b.meta_key = 'level'
AND c.meta_key = '_post_main_intro'
这是下去的方法吗?
答案 0 :(得分:2)
您的查询中需要两次元数据表:
SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro
FROM wp_posts a
LEFT JOIN wp_postmeta b ON a.ID = b.post_id
LEFT JOIN wp_postmeta c ON a.ID = c.post_id
WHERE b.meta_key = 'level'
AND c.meta_key = '_post_main_intro'
编辑:忘记在列中包含第三个表
答案 1 :(得分:0)
尝试:
SELECT a.post_title, b.meta_key, b.meta_value
FROM wp_posts a
LEFT JOIN wp_postmeta b ON (a.ID = b.post_id)
WHERE b.meta_key = 'level' OR b.meta_key = '_post_main_intro'
答案 2 :(得分:0)
那是因为您已将搜索限制为“级别”
WHERE b.meta_key = 'level'
只需删除该部分,它就应该为您提供所有