自定义帖子类型和多个自定义字段的SQL查询

时间:2013-03-02 00:07:49

标签: sql wordpress

我正在使用WP Data Tables从SQL DB创建表。在wordpress后端,使用的示例代码如下所示:

SELECT post_id, post_date
FROM wp_posts
WHERE post_type =  'custom_post_type'
AND post_status =  'publish'

我试图从post meta获取自定义字段值。这是我到目前为止所拥有的......

SELECT post_id, post_date
FROM wp_posts
WHERE post_type =  'custom_post_type'
AND post_status =  'publish'
AND SELECT custom_field_key_1, custom_field_key_2, custom_field_key_3
FROM wp_postmeta
WHERE post_id = post_id

更新:

我发现需要p.ID而不是post_id,我需要搜索meta_key。有点像...

SELECT p.post_title, 
       p.post_date,
       pm.meta_key = 'custom_field_key'
FROM wp_posts p 
INNER JOIN wp_postmeta pm 
ON p.ID = pm.post_id
WHERE p.post_type = 'custom_post_type'
AND p.post_status = 'publish'

4 个答案:

答案 0 :(得分:4)

使用INNER JOIN

SELECT p.post_id, 
       p.post_date, 
       pm.custom_field_key_1, 
       pm.custom_field_key_2, 
       pm.custom_field_key_3
FROM wp_posts p 
   INNER JOIN wp_postmeta pm 
       ON p.post_id = pm.post_id
WHERE p.post_type = 'custom_post_type'
   AND p.post_status = 'publish'

答案 1 :(得分:0)

假设支持标准SQL,您将需要类似这样的内容(未经测试):

SELECT w.post_id, w.post_date, m.custom_field_key_1, m.custom_field_key_2, m.custom_field_key_3
FROM wp_posts w, wp_postmeta m
WHERE post_type =  'custom_post_type' AND post_status =  'publish'
AND w.post.id = m.post.id

答案 2 :(得分:0)

你可以试试这个。

SELECT p.post_id, p.post_date,
    pm.custom_field_key_1, pm.custom_field_key_2, pm.custom_field_key_3
FROM wp_posts p
JOIN wp_postmeta pm ON p.post_id = pm.post_id
WHERE p.post_type =  'custom_post_type'
AND p.post_status =  'publish'

答案 3 :(得分:0)

好的,即使您更新了答案。我举了你的例子,我解决了这个问题:

SELECT p.ID, 
       p.post_title, 
       pm.meta_value as 'value1', 
       pma.meta_value as 'value2'

FROM  wp_posts p 
      INNER JOIN wp_postmeta AS pm  ON pm.post_id  = p.ID
      INNER JOIN wp_postmeta AS pma ON pma.post_id = p.ID

WHERE
      pma.meta_key = 'custom_field_key_1' AND
      pm.meta_key = 'custom_field_key_2' AND

      p.post_type = 'your_post_type' AND 
      p.post_status = 'publish'

所以,我在同一个表中使用别名ASINNER JOINwp_postmeta post_id使用别名{/ 1}}。

参考文献: Multiple Inner join same table

通过执行此操作,您将获得包含帖子和所选自定义字段的数组:

array(1) {
    [0]=> object(stdClass)#341 (4) {
          ["ID"]=>    string(1) "1123"
          ["post_title"]=>  string(15) "Your post title"
          ["custom_field_key_1"]=> string(12) "Your value 1 "
          ["custom_field_key_2"]=> string(29) "Your value 2"
}

您可以根据需要添加任意数量的别名和meta_key。希望这有帮助!